ASP.NET Paging next page button does not work properly - c#

I'am trying to divide all of my products that i listed by using a repeater to pages. For example there are 3 pages. The paging looks well but when i click to next page button it is going to page 4 which is not exist actually. What can be the reason ? Implementation is below.
private void showShoes()
{
dataInThePage = new PagedDataSource()
{
DataSource = ap.getShoes(),
AllowPaging = true,
PageSize = 2,
CurrentPageIndex = pageNo
};
shoeRepeater.DataSource = dataInThePage;
shoeRepeater.DataBind();
pageAmount = dataInThePage.PageCount - 1;
//
pageInfoLabel.Text = "Page: " + (dataInThePage.CurrentPageIndex + 1) + "/" + dataInThePage.PageCount + " - Number of Shoes: " + (dataInThePage.DataSourceCount);
//
previousButton.Enabled = !dataInThePage.IsFirstPage;
nextButton.Enabled = !dataInThePage.IsLastPage;
}
private int pageNo
{
get
{
if (ViewState["pageNumber"] != null)
return Convert.ToInt32(ViewState["pageNumber"]);
return 0;
}
set
{
ViewState["pageNumber"] = value;
}
}
private int pageAmount
{
get
{
if (ViewState["pageNumber"] != null)
return Convert.ToInt32(ViewState["pageNumber"]);
return 0;
}
set { ViewState["pageNumber"] = value; }
}
public PagedDataSource dataInThePage { get; set; }
protected void previousButton_Click(object sender, EventArgs e)
{
pageNo -= 1;
showShoes();
}
protected void nextButton_Click(object sender, EventArgs e)
{
pageNo += 1;
showShoes();
}
Front-end:
<ajaxToolkit:TabPanel ID="TabPanel5" runat="server">
<HeaderTemplate>Show Shoes</HeaderTemplate>
<ContentTemplate runat="server">
<asp:Repeater ID="shoeRepeater" runat="server">
<HeaderTemplate></HeaderTemplate>
<ItemTemplate>
<table border="1" style="border-color:#ff9900; width:400px; font-weight:bold; font-family:'Oswald', Arial, sans-serif;">
<tr>
<td rowspan="6" style="width:150px; height:150px;">
<image src="shoeImages/<%#DataBinder.Eval(Container.DataItem,"ImagePath") %>"></image>
</td>
</tr>
<tr>
<td>
<%#DataBinder.Eval(Container.DataItem,"BrandName") %> - <%#DataBinder.Eval(Container.DataItem,"ModelName") %>
</td>
</tr>
<tr>
<td>
Price: $<%#DataBinder.Eval(Container.DataItem,"Price") %>
</td>
</tr>
<tr>
<td>
Size: <%#DataBinder.Eval(Container.DataItem,"Size") %>
</td>
</tr>
<tr>
<td>
Color: <%#DataBinder.Eval(Container.DataItem,"PrimaryColor") %> - <%#DataBinder.Eval(Container.DataItem,"SecondaryColor") %>
</td>
</tr>
<tr>
<td>
Quantity: <%#DataBinder.Eval(Container.DataItem,"Quantity") %>
</td>
</tr>
</table>
</ItemTemplate>
<FooterTemplate></FooterTemplate>
</asp:Repeater>
<div style="width:600px; height:20px;">
<div style="width:50px; height:100%; float:left">
<asp:Button ID="previousButton" runat="server" OnClick="previousButton_Click" Text="<<" Width="50px"/>
</div>
<div style="width:500px; height:100%; float:left; text-align:center">
<asp:Label ID="pageInfoLabel" runat="server" Text=" "></asp:Label>
</div>
<div style="width:50px; height:100%; float:left">
<asp:Button ID="nextButton" runat="server" OnClick="nextButton_Click" Text=">>" Width="50px"/>
</div>
</div>
</ContentTemplate>
</ajaxToolkit:TabPanel>

I had to guess on a number of things, but I was able to take the posted code and get it to work in VS 2010 using an ASP.NET 4.0 project.
Here are the things I did to get it working:
Add a Shoe POCO with the 8 public properties referenced in the .aspx page (not shown)
Add a FakeShoeRepository class that has a private static List<Shoe> with 9 shoes (not shown)
Add a static method called getShoes() that returns a reference to the private member variable of the repository (not shown)
Set the dataInThePage.DataSource = FakeShoeRepository.getShoes() (not shown)
Add a Page_Load() event
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
pageNo = 0;
showShoes();
}
}
Remove the pageAmount property
Remove the one place pageAmount was being set in the showShoes() method (this was effectively setting ViewState["pageNumber"] = PageCount - 1)
The last two items are where the actual problem was in the provided code.

Related

DataList button fires every time the page is refreshed

I have a link button in a DataList in a shopping cart that works fine. Once they have selected the product, if they refresh the page, it will retrigger this button.
<asp:DataList runat="server" ID="rpCategories" RepeatColumns="4" RepeatDirection="Horizontal" OnItemCommand="rpCategories_ItemCommand"
ItemStyle-HorizontalAlign="Center" ClientIDMode="Static" ItemStyle-CssClass="bigLink">
<ItemTemplate>
<table>
<tr>
<td>
<div class="<%=EnrollmentPacksBottomBox %>">
<div class="enrollment1ProImage">
<img src="../../Common/Images/products/large/<%# Eval("largeImages") %>" width="250" />
</div>
<div class="enrollment1ProductName">
<%# Eval("productName") %>
</div>
<div class="enrollment1DescriptionBottom1">
<%# Eval("description") %>
</div>
<div class="enrollment1Price">
<table>
<tr>
<td>
<%# String.Format(CultureInfo.GetCultureInfo(MyCulture), "{0:c}", Eval("price")) %>
</td>
<td>
<div class="enrollment1PvSpacer"></div>
</td>
<td>PV:
<%# Eval("pv") %>
</td>
</tr>
</table> <%-- new amount, and buttons- start--%>
<table class="cartButtonsHolder">
<tr>
<td>
<div class="">
<button type="button" style="border: none; background-color: white;">
<table class="cartButtons">
<tr>
<td rowspan="2">
<asp:TextBox runat="server" ID="quantityHolder" Text='<%# Eval("quantity") %>' CssClass="QuantityBox"/>
</td>
<td>
<asp:LinkButton runat="server" ID="upButton" OnClick="AddItem" CssClass="caretButton fas fa-caret-up" Text="" />
</td>
</tr>
<tr>
<td>
<asp:LinkButton runat="server" ID="downButton" OnClick="SubtractItem" CssClass="caretButton fas fa-caret-down fa-m" Text="" />
</td>
</tr>
</table>
</button>
</div>
</td>
<td>
<asp:LinkButton runat="server" OnClick="SelectPro1Bottom"><div class="enrollment1SelectButton"> Add to Cart</div></asp:LinkButton>
</td>
</tr>
</div>
</div>
</td>
</tr>
</table>
</ItemTemplate>
</asp:DataList>
The code behind looks like this:
protected void SelectPro1Bottom(object sender, EventArgs e)
{
DAL oDal = new DAL();
var btn = (LinkButton)sender;
//var btn = (HtmlButton)sender;
var item = (DataListItem)btn.NamingContainer; //RepeaterItem
int index = item.ItemIndex;
int quantity = 0;
GetSelected(index);
Session["amount"] = 1;
//pull in the quantity
Quantities = Session["formatQuantities"] as List<int>;
List<OrderUserTypeHolder> TempHolder = new List<OrderUserTypeHolder>();
OrderUserTypeHolder oh = new OrderUserTypeHolder();
TempHolder = Session["userTypeHolder"] as List<OrderUserTypeHolder>;
int userType = 0;
int hasAutoship = 0;
string country = "";
userType = TempHolder[0].UserType;
hasAutoship = TempHolder[0].HasAutoship;
country = TempHolder[0].Country;
ProductIdList.Clear();
using (oDal)
{
//dist
if (userType == 2 && hasAutoship == 1)
{
SqlDataReader rd = oDal.ProductsGetAllByDescLengthAutoReader(country);
while (rd.Read())
{
ProductIdList.Add(Convert.ToInt32(rd["productId"]));
}
}
else if (userType == 2)
{
SqlDataReader rd = oDal.ProductsGetAllByDescLengthDistReader(country);
while (rd.Read())
{
ProductIdList.Add(Convert.ToInt32(rd["productId"]));
}
}
//pc
else if (userType == 3)
{
SqlDataReader rd = oDal.ProductsGetAllByDescLengthPcReader(country);
while (rd.Read())
{
ProductIdList.Add(Convert.ToInt32(rd["productId"]));
}
}
//retail
else
{
SqlDataReader rd = oDal.ProductsGetAllByDescLengthRetailReader(country);
while (rd.Read())
{
ProductIdList.Add(Convert.ToInt32(rd["productId"]));
}
}
oDal.Dispose();
}
//make sure we don't have an empty array
if (Quantities.Count > 0)
{
quantity = Quantities[index];
}
else
{
quantity = 1;
}
int productId = ProductIdList[index];
AddItemsToCart(productId, quantity, hasAutoship);
}
I have tried a wide variety of fixes including feeding a value of null to my datasource, changing my view state, and moving it inside !isPostback (the link button won't work). Every time you click the linkbutton it reloads the page (does not go in !isPostback) and refreshing the page has the same effect. Every time the page is rereshed, it will add another of the last item selected to the cart. I have tried everything I could think of and everything I have found online over the past several hours.
Any suggestions would be greatly appreciated!

How to get the hidden field value to be set within a table that uses pagination?

I have a repeater inside an html table that uses pagination. I want to be able to read the values of the hidden fields within the repeater in the code behind, but only the hidden field values of the table page being viewed on postback seem to be set when I'm in the code behind. How do I make it so the hidden field values are set for each repeater item regardless of the table page?
HTML:
<div id="divTableContainer" runat="server">
<table id="tblAssessmentExtracts" class="table table-striped table-sm table-hover ">
<thead>
<tr>
<th>Consumer</th>
<th>Assessment</th>
<th>Completed</th>
<th></th>
</tr>
</thead>
<tbody>
<asp:Repeater ID="rptAssessmentExtractQueue" runat="server" OnItemCommand="rptAssessmentExtractQueue_ItemCommand">
<ItemTemplate>
<tr class="assessment-extract-block">
<td><%# Eval("ConsumerName") %>
</td>
<td><%# Eval("SurveyName") %>
</td>
<td><%# Eval("CompletionDate") %></td>
<td class="buttoncell">
<asp:LinkButton ID="btnExportRecord" runat="server" Text="Export" CommandArgument='<%# Eval("Id") %>' />
<asp:HiddenField ID="hdAssessmentId" runat="server" Value='<%# Eval("Id") %>' />
<span class="selection"><asp:HiddenField ID="hdAssessmentSelected" runat="server" /></span>
</td>
</tr>
</ItemTemplate>
</asp:Repeater>
</tbody>
</table>
</div>
JavaScript:
<script type="text/javascript">
$(document).ready(function () {
var table = $('#tblAssessmentExtracts').DataTable({
"pageLength": 25,
});
});
function selectBlock(elementIndex, element) {
var selectedField = $(element).find('.selection input[type="hidden"]');
if ($(element).hasClass("table-info") === false) {
$(element).addClass("table-info");
}
if (selectedField.length > 0) {
selectedField.val("true");
}
}
function deselectBlock(elementIndex, element) {
var selectedField = $(element).find('.selection input[type="hidden"]');
if ($(element).hasClass("table-info")) {
$(element).removeClass("table-info");
}
if (selectedField.length > 0) {
selectedField.val("");
}
}
$('.assessment-extract-block').click(function (e) {
var selectedField = $(this).find('.selection input[type="hidden"]');
if (selectedField.length > 0) {
if (selectedField.val() === "true") {
deselectBlock(0, $(this));
} else {
selectBlock(0, $(this));
}
}
});
</script>
C#:
private IEnumerable<long> getSelectedResponses()
{
List<long> assessmentIds = new List<long>();
foreach (RepeaterItem riAssessment in rptAssessmentExtractQueue.Items)
{
HiddenField hdAssessmentSelected = riAssessment.FindControl("hdAssessmentSelected") as HiddenField;
HiddenField hdAssessmentId = riAssessment.FindControl("hdAssessmentId") as HiddenField;
bool export = false;
if (bool.TryParse(hdAssessmentSelected.Value, out export) && export)
{
long assessmentId;
if (long.TryParse(hdAssessmentId.Value, out assessmentId) && assessmentId > 0)
{
assessmentIds.Add(assessmentId);
}
}
}
return assessmentIds;
}

Trying to display a phone number as it is entered with buttons using asp.net

I am working on a project in which I am trying to have an empty label populate with the numbers that are being clicked. However, I am having trouble with my code behind my web form and cannot get it to work. My code behind:
public partial class WebForm : System.Web.UI.Page
{
ArrayList phoneNumber = new ArrayList() { };
int counter = 0;
protected void Page_Load(object sender, EventArgs e)
{
}
protected void btnNum1_Click(object sender, EventArgs e)
{
counter++;
phoneNumber[counter - 1] = 1;
lblNumbers.Text = phoneNumber.ToString();
}
protected void btnNum2_Click(object sender, EventArgs e)
{
counter++;
phoneNumber[counter - 1] = 1;
lblNumbers.Text = phoneNumber.ToString();
}
My web form:
<form id="form1" runat="server">
<div class="container">
<asp:Image class="img-fluid d-block mx-auto" ID="imgLogo" runat="server" ImageUrl="~/Images/logo.png"/>
<div style="text-align:center; font-size:x-large; font-weight:800">
<asp:Label ID="lblNumbers" runat="server" Text=""></asp:Label>
</div>
<table class="table table-bordered" style="margin:auto; width:250px; height:342px; background-image:url(Images/Telephone-keypad.png); background-repeat:no-repeat; background-position:center;" >
<tbody>
<tr>
<asp:ListBox ID="ListBox1" runat="server"></asp:ListBox>
<td><asp:Button ID="btnNum1" runat="server" OnClick="btnNum1_Click"/></td>
<td><asp:Button ID="btnNum2" runat="server" OnClick="btnNum2_Click"/></td>
<td><asp:Button ID="btnNum3" runat="server" OnClick="btnNum3_Click"/></td>
</tr>
<tr>
<td><asp:Button ID="btnNum4" runat="server" OnClick="btnNum4_Click"/></td>
<td><asp:Button ID="btnNum5" runat="server" OnClick="btnNum5_Click"/></td>
<td><asp:Button ID="btnNum6" runat="server" OnClick="btnNum6_Click"/></td>
</tr>
<tr>
<td><asp:Button ID="btnNum7" runat="server" OnClick="btnNum7_Click"/></td>
<td><asp:Button ID="btnNum8" runat="server" OnClick="btnNum8_Click"/></td>
<td><asp:Button ID="btnNum9" runat="server" OnClick="btnNum9_Click"/></td>
</tr>
<tr>
<td><asp:Button ID="btnStar" runat="server" OnClick="btnStar_Click"/></td>
<td><asp:Button ID="btnNum0" runat="server" OnClick="btnNum0_Click"/></td>
<td><asp:Button ID="btnPound" runat="server" OnClick="btnPound_Click"/></td>
</tr>
</tbody>
</table>
</div>
</form>
When each button is clicked, I want the numbers that are clicked to display in the label as they are clicked. Currently, when I click on a button, it gives me an error page that states:
Index was out of range. Must be non-negative and less than the size of the collection.
It also includes this:
Source Error:
Line 21: {
Line 22: counter++;
Line 23: phoneNumber[counter - 1] = 1;
Line 24: lblNumbers.Text = phoneNumber.ToString();
Line 25: }
Can someone please help?
Asp.net Pages are stateless, meaning your variables like "int counter" does not maintain its value between post backs. Because of this it will always be zero, you are then subtracting 1, which results in -1 which will result in the error that you are getting. Try saving the value in a session variable, or for even better results you could use javascript instead.
You need to append the value of the clicked number to the value in the label. Since you're in Webforms you can store it in ViewState instead of using a session variable (unless the user can come and go and your requirement is to preserve it).
I'd try something like this:
protected void btnNum1_Click(object sender, EventArgs e)
{
appendNumber(1);
}
.
.
.
private void appendNumber(int number)
{
counter++;
phoneNumber[counter - 1] = number;
ViewState["phoneNumber"] = phoneNumber.ToString();
}
protected void Page_Load(object sender, EventArgs e)
{
if(!String.IsNullOrEmpty(ViewState["phoneNumber"].ToString()))
{
lblNumbers.Text = ViewState["phoneNumber"].ToString()
}
}
static int counter = 0;
use this ...and it will hold values between postbacks

How to access values from dynamically added user control?

I want to get values from dynamically added user control
I'm trying but count comes as 0 so condition failed
Code:
private const string VIEWSTATEKEY = "ContactCount";
protected void Page_Load(object sender, EventArgs e)
{
if (!Page.IsPostBack)
{
//Set the number of default controls
ViewState[VIEWSTATEKEY] = ViewState[VIEWSTATEKEY] == null ? 1 : ViewState[VIEWSTATEKEY];
//Load the contact control based on Vewstate key
LoadContactControls();
}
}
private void LoadContactControls()
{
for (int i = 0; i < int.Parse(ViewState[VIEWSTATEKEY].ToString()); i++)
{
rpt1.Controls.Add(LoadControl("AddVisaControl.ascx"));
}
}
protected void addnewtext_Click(object sender, EventArgs e)
{
ViewState[VIEWSTATEKEY] = int.Parse(ViewState[VIEWSTATEKEY].ToString()) + 1;
LoadContactControls();
}
EDIT
Here is the problem count takes as 0 so condition failed loop comes out
private void saveData()
{
foreach (var control in rpt1.Controls)
{
var usercontrol = control as VisaUserControl;
string visaNumber = usercontrol.TextVisaNumber;
string countryName = usercontrol.VisaCountry;
}
}
}
protected void Save_Click(object sender, EventArgs e)
{
saveData();
}
.ascx.cs
public string TextVisaNumber
{
get { return txtUser.Text; }
set { txtUser.Text = value; }
}
public string VisaCountry
{
get { return dropCountry.SelectedValue; }
set { dropCountry.SelectedValue = value; }
}
.ascx
<%# Control Language="C#" AutoEventWireup="true" CodeBehind="AddVisaControl.ascx.cs" EnableViewState="false" Inherits="Pyramid.AddVisaControl" %>
<%# Register assembly="BasicFrame.WebControls.BasicDatePicker" namespace="BasicFrame.WebControls" tagprefix="BDP" %>
<div id="divreg" runat="server">
<table id="tbl" runat="server">
<tr>
<td>
<asp:Label ID="lbl2" runat="server"></asp:Label>
</td>
</tr>
<tr>
<td> Visa Number:</td>
<td><asp:TextBox ID="txtUser" Width="160px" runat="server"/></td>
<td> Country Name:</td>
<td><asp:DropDownList ID="dropCountry" Width="165px" runat="server"></asp:DropDownList></td>
</tr>
<tr>
<td> Type of Visa:</td>
<td><asp:DropDownList ID="dropVisa" Width="165px" runat="server"></asp:DropDownList></td>
<td> Type of Entry:</td>
<td><asp:DropDownList ID="dropEntry" Width="165px" runat="server"></asp:DropDownList></td>
</tr>
<tr>
<td> Expiry Date</td>
<td><BDP:BasicDatePicker ID="basicdate" runat="server"></BDP:BasicDatePicker></td>
<td>
<asp:Button ID="btnRemove" Text="Remove" runat="server" OnClick="btnRemove_Click" />
</td>
</tr>
</table>
</div>
Any ideas? Thanks in advance
You need to create public property in your user control.
And access that property through the id of the user control.
See this and This question.
Always assign id to the controls you are adding its a good practice.
Control ctrl = Page.LoadControl("~/UserControls/ReportControl.ascx");
ctrl.ID = "UniqueID";
Also since you are adding controls dynamically you need to manage view state of the same, or add third party controls who do this part for you.

c# postback dropdownlist always choose first value

I want to insert the selected item of drop down list into database but my drop down list keep returns the first option . auto post back is false .
codes here :
dropTask() = drop down list where I populate it from database.
protected void Page_Load(object sender, EventArgs e)
{
if (!Page.IsPostBack)
{
dropTask();
}
}
protected void AjaxFileUpload1_UploadComplete(object sender, AjaxControlToolkit.AjaxFileUploadEventArgs e)
{
String pathdirectory = (dropListActivity.SelectedItem.Text+"/");
String filepathImage = (pathdirectory + e.FileName);
EnsureDirectoriesExist(pathdirectory);
AjaxFileUpload1.SaveAs(Server.MapPath(filepathImage));
Session["filepathImage"] = filepathImage;
}
i had checked the value return from drop down list using label :
protected void btnDone_Click(object sender, EventArgs e)
{
if (Session["filepathImage"] != null)
{
string filepathImage = Session["filepathImage"] as string;
Label1.Text = filepathImage;
}
}
the label text show the first option of the drop down list value instead of the choice I have chosen . Please enlighten me on this .
ASPX:
<tr>
<td>
<h2>Upload your Story!</h2>
<asp:ToolkitScriptManager ID="ToolkitScriptManager1" runat="server">
</asp:ToolkitScriptManager>
</td>
</tr>
<tr>
<td colspan = "2"></td>
</tr>
<tr>
<td>
<b>Select Activity:</b>
</td>
<td>
<asp:DropDownList ID="dropListActivity" runat="server"
onselectedindexchanged="dropListActivity_SelectedIndexChanged">
</asp:DropDownList>
</td>
</tr>
<tr>
<td colspan = "2"></td>
</tr>
<tr>
<td>
<b>Story Title:</b>
</td>
<td>
<asp:TextBox ID="txtStoryTitle" runat="server"
ontextchanged="txtTitle_TextChanged" AutoPostBack="True"></asp:TextBox>
</td>
</tr>
<tr>
<td class="style1">
<b>Upload your files here:</b><br />
Multiple Images and 1 Audio file only.
</td>
<td class="style1">
<asp:AjaxFileUpload ID="AjaxFileUpload1" runat="server"
onuploadcomplete="AjaxFileUpload1_UploadComplete"
/>
</td>
</tr>
<tr>
<td colspan = "2"></td>
</tr>
<tr>
<td>
<asp:Label ID="Label1" runat="server" ></asp:Label>
</td>
<td>
<asp:Button ID="btnDone" runat="server" Text="Done" onclick="btnDone_Click" />
</td>
</tr>
DropListActivity.SelectedItem.ToString should do the trick. There are a few other things you should keep in mind:
Make sure you are not populating the dropdownlist on a postback.
Selected value will only be available at the sever if the portion of
the page containing the dropdownlist control is posted back.i.e if
you are using an update panel your dropdownlist should be present
within that panel or if you are posting back the entire page then there wont be any problem at all provided you meet the first criteria.
Your event handler dropListActivity_SelectedIndexChanged will
always be fired when a page is posted back and the seleceted index
has changed. The event handler dropListActivity_SelectedIndexChanged will be called after the page_load subroutine is executed.
I assume you need something like:
private void SaveSelected()
{
ViewState["SelectedItem"] = dropListActivity.SelectedItem;
}
which you use on dropListActivity_SelectedIndexChanged and
private void LoadSelected()
{
if (ViewState["SelectedItem"] != null)
dropListActivity.SelectedItem = (ListItem)ViewState["SelectedItem"];
}
which you call after dropTask();
Please, refer to this post's answer
in dropListActivity_SelectedIndexChanged event do like
if(dropListActivity.Items.Count > 0)
{
ViewState["DropDownSelectedValue"] = dropListActivity.Item.SelectedValue;
}
and on Load or databind of drop down list event write
if(ViewState["DropDownSelectedValue"] != null && dropListActivity.Items.Count > 0)
{
dropListActivity.SelectedValue = ViewState["DropDownSelectedValue"].ToString();
}

Categories

Resources