Save values on Postback - asp.net

I have been doing custom paging for a datagrid where i retrieve only 10 values per page. So, I started doing it this way :
<asp:GridView ID="grid1" runat="server"
> </asp:GridView>
<asp:Button ID="Btn_Previous" CommandName="Previous" runat="server"
OnCommand="ChangePage" Text="Previous" />
<asp:Button ID="Btn_Next" runat="server" CommandName="Next" OnCommand="ChangePage"
Text="Next" />
<asp:Label ID="lblTotalPages" runat="server"></asp:Label>
<asp:Label ID="lblCurrentPage" runat="server"></asp:Label>
protected int currentPageNumber = 1;
protected const int PAGE_SIZE = 10;
protected int startrowindex=1;
protected void Page_Load(object sender, EventArgs e)
{
BindData();
}
private void BindData()
{
using (SqlConnection conn = new SqlConnection("Data Source=NISHANTH-PC\\SQLEXPRESS;Initial Catalog=Northwind;Integrated Security=True"))
{
conn.Open();
SqlCommand myCommand = new SqlCommand("GetProductsPaged",
conn);
myCommand.CommandType = CommandType.StoredProcedure;
myCommand.Parameters.AddWithValue("#startRow",
startrowindex);
myCommand.Parameters.AddWithValue("#maximumRows", PAGE_SIZE);
myCommand.Parameters.Add("#totalRows", SqlDbType.Int, 4);
myCommand.Parameters["#totalRows"].Direction = ParameterDirection.Output;
SqlDataAdapter ad = new SqlDataAdapter(myCommand);
DataSet ds = new DataSet();
ad.Fill(ds);
grid1.DataSource = ds;
grid1.DataBind();
double totalRows = (int)myCommand.Parameters["#totalRows"].Value;
lblTotalPages.Text = CalculateTotalPages(totalRows).ToString();
lblCurrentPage.Text = currentPageNumber.ToString();
if (currentPageNumber == 1)
{
Btn_Previous.Enabled = false;
if (Int32.Parse(lblTotalPages.Text) > 0)
{
Btn_Next.Enabled = true;
}
else
Btn_Next.Enabled = false;
}
else
{
Btn_Previous.Enabled = true;
if (currentPageNumber == Int32.Parse(lblTotalPages.Text))
Btn_Next.Enabled = false;
else Btn_Next.Enabled = true;
}
conn.Close();
}
}
private int CalculateTotalPages(double totalRows)
{
int totalPages = (int)Math.Ceiling(totalRows / PAGE_SIZE);
return totalPages;
}
protected void ChangePage(object sender, CommandEventArgs e)
{
switch (e.CommandName)
{
case "Previous":
currentPageNumber = currentPageNumber - 1;
startrowindex = startrowindex - 10;
break;
case "Next":
currentPageNumber = currentPageNumber + 1;
startrowindex = startrowindex + 10;
break;
}
BindData();
}
Basically, my problem has been that the grid works fine when the page loads. Then, since previous is hidden, when i click next it goes to second page and retrieves values perfectly. But when i click either on next or previous now, it goes all wrong. The reason i think is that, when I come back the currentpagenumber value at top is again becoming 1and startroeindex also becomes 1. Can u please let me know the way i can handle this?

I don't know your aspx page, but you need a way to send the previous page number. Otherwise, your script doesn't know what next means except 1+1. How do you change pages? Hyperlinks? If so, send the last page in a form field or query string.

first thing is that you are loading BindData on each and every post back, you must only call it on first time load.
Second thing, you are storing the in label, lblCurrentPage.Text = currentPageNumber.ToString(); So why dont you utilize the same and store it again on page_load event.
I have here provided the page_load event try this.
protected void Page_Load(object sender, EventArgs e)
{
currentPageNumber = Convert.ToInt32(lblCurrentPage.Text);
if(!IsPostback)
{
BindData();
}
}
please add default value for lblCurrentPage.Text to 1.

Related

How to determine which button is clicked in dynamically created DataTable

I'm creating dynamically data Table bound to Grid View. Every row is populated with button. When i determine which button is clicked on the row, i want to get the current value of cell in clicked button in that row and modify her.Help!
Markup
<asp:GridView ID="GridView2" runat="server"
OnRowDataBound="GridView2_RowDataBound">
<Columns>
<asp:TemplateField>
<ItemTemplate>
<asp:Button ID="btnTest" runat="server"
CommandName="odzemi"
CssClass="button2"
Font-Bold="True"
Text="-"
Width="100px"
OnClick="btnTest_Click" />
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
//in this way a create row
private void AddNewRecordRowToGrid()
{
int counter;
if (Request.Cookies["kasa"] == null)
counter = 0;
else
{
counter = int.Parse(Request.Cookies["kasa"].Value);
}
counter++;
Response.Cookies["kasa"].Value = counter.ToString();
Response.Cookies["kasa"].Expires = DateTime.Now.AddYears(2);
if (ViewState["Markici"] != null)
{
DataTable dtCurrentTable = (DataTable)ViewState["Markici"];
DataRow drCurrentRow = null;
if (dtCurrentTable.Rows.Count > 0)
{
for (int i = 1; i <= dtCurrentTable.Rows.Count; i++)
{
HttpCookie cookie = Request.Cookies["Democookie"];
drCurrentRow = dtCurrentTable.NewRow();
drCurrentRow["FirmaID"] = Request.Cookies["firma"].Value;
drCurrentRow["Godina"] = Request.Cookies["godina"].Value;
drCurrentRow["KasaID"] = Request.Cookies["kasa"].Value;
drCurrentRow["MarkicaID"] = Request.Cookies["kasa"].Value;
drCurrentRow["Datum"] = DateTime.Now;
drCurrentRow["Masa"] = Session["masa39"];
drCurrentRow["VrabotenID"] = Session["New"];
drCurrentRow["Artikal"] = Label3.Text;
drCurrentRow["Cena1"] = Label4.Text;
//this is where i need to make changes
drCurrentRow["Kolicina"] = Label5.text;
drCurrentRow["Smena"] = Session["smena1"];
drCurrentRow["VkIznos"] = Label6.Text;
drCurrentRow["VkDanok"] = Label8.Text;
drCurrentRow["SySDatum"] = DateTime.Now;
drCurrentRow["Vid"] = Label23.Text;
drCurrentRow["Edmera"] = Label10.Text;
drCurrentRow["ArtikalID"] = Label33.Text;
}
//Removing initial blank row
if (dtCurrentTable.Rows[0][0].ToString() == "")
{
dtCurrentTable.Rows[0].Delete();
dtCurrentTable.AcceptChanges();
}
//Added New Record to the DataTable
dtCurrentTable.Rows.InsertAt(drCurrentRow,0);
//storing DataTable to ViewState
ViewState["Markici"] = dtCurrentTable;
//binding Gridview with New Row
GridView2.DataSource = dtCurrentTable;
GridView2.DataBind();
}
}
}
//in this button i call that method
protected void Button9_Click(object sender, EventArgs e)
{
AddNewRecordRowToGrid();
}
//
and here i'm determine clicked button of row, and here in this
dtCurrentTable.Rows[clickedIndex]["Kolicina"]= "" i need to
get cureent value of cell which is different in every row.
protected void btnTest_Click(object sender, EventArgs e)
{
DataTable dtCurrentTable = (DataTable)ViewState["Markici"];
var clickedRow = ((Button)sender).NamingContainer as GridViewRow;
var clickedIndex = clickedRow.RowIndex;
//so here i want to get current value of cell, and modify her
dtCurrentTable.Rows[clickedIndex]["Kolicina"] = " ";
GridView2.DataSource = dtCurrentTable;
GridView2.DataBind();
}
Try this.
protected void btnTest_Click(object sender, EventArgs e)
{
var clickedRow = ((Button)sender).NamingContainer as GridViewRow;
var clickedIndex = clickedRow.RowIndex;
}
Provided your GridView does not have sorting or paging enabled, from this clickedIndex, we can get the corresponding Row of the DataTable like this.
dtCurrentTable.Rows[clickedIndex]["Kolicina"] = "StackOverflow";
In the RowDataBound event, the EventArgument e should have the index of the current item bound in it. The code e.Row.RowIndex will return the index of the row in the Grid, not necessarily the datasource when you have paging applied. There is a 'DataItemIndex' property, another index that may give you what you are looking for, depending on what you are trying to do.
The grid also exposes the Rows collection, which you can use a foreach to loop through each one, and access that way too.
Note, the Rows on postback will only be based on the markup posted back through viewstate; the grid knows nothing about your data source (unless you rebind on every postback).

checkboxlist selectedindexchanged event c# not working

I've got a checkboxlist on my asp.net page. I'm populating it with countries. I've added a "SelectedIndexChanged" event that is supposed to check that if one of the selected countries is Africa, it should make a textbox visible, otherwise visible=false if it is not selected. I have changed the AutoPostback to true. But the problem that I'm having is that it is not doing an autopostback (it's not going into the method at all). Could somebody please help me on this?
This is what I've done:
<div id="div1" style="overflow-x:auto; width:100%; max-width:100%; height:150px; max-height:150px;" runat="server">
<asp:CheckBoxList ID="lstLocations" CssClass="CheckBoxList" runat="server" Width="40%" Height="100%" AutoPostBack="True" OnSelectedIndexChanged="lstLocations_SelectedIndexChanged" >
</asp:CheckBoxList>
</div>
Populating the checkboxlist:
private void CreateRegionList()
{
lstLocations.Items.Clear();
cn = new SqlConnection(GetConnectionString());
SqlCommand myCmd = new SqlCommand("SELECT ID, Region FROM CanonSALeads_Region ORDER BY Region", cn);
cn.Open();
SqlDataReader myReader = myCmd.ExecuteReader();
lstLocations.AutoPostBack = false;
lstLocations.CellPadding = 5;
lstLocations.CellSpacing = 5;
lstLocations.RepeatColumns = 1;
lstLocations.RepeatDirection = RepeatDirection.Vertical;
lstLocations.RepeatLayout = RepeatLayout.Flow;
lstLocations.TextAlign = TextAlign.Right;
lstLocations.CssClass = "CheckBoxList";
if (myReader.HasRows)
{
while (myReader.Read())
{
CheckBox cb = new CheckBox();
cb.ID = myReader[0].ToString();
cb.Text = myReader[1].ToString();
cb.AutoPostBack = false;
cb.CssClass = "CheckBox";
lstLocations.Items.Add(new ListItem(myReader[1].ToString(), myReader[0].ToString()));
lstLocations.Controls.Add(new LiteralControl("<br>"));
}
}
cn.Close();
myReader.Close();
}
And this is my selectedIndexChanged event:
protected void lstLocations_SelectedIndexChanged(object sender, EventArgs e)
{
string value = null;
try
{
foreach (ListItem checkBox in lstLocations.Items)
{
if (checkBox.Selected == true)
{
value = checkBox.Text;
if (value == "Africa")
{
txtCountryOfAfrica.Visible = true;
lblAfricaCountry.Visible = true;
}
}
else
{
value = checkBox.Text;
if (value == "Africa")
{
txtCountryOfAfrica.Visible = false;
lblAfricaCountry.Visible = false;
}
}
}
}
catch (Exception ex)
{
string msg = "Select Error:";
msg += ex.Message;
throw new Exception(msg);
}
}
Page_Load method:
protected void Page_Load(object sender, EventArgs e)
{
string userName = System.Security.Principal.WindowsIdentity.GetCurrent().Name;
txtUser.Text = userName;
if (!IsPostBack)
{
ContainerDocumentation.ActiveTab = tabAddCustomer;
PopulateSector();
CreateRegionList();
PopulateOpportunitySource();
CreatelstProductGroupList();
PopulateStatus();
PopulateTenders();
PopulateOtherOpportunityType();
}
}
My guess: you are calling CreateRegionList in Page_Load without checking the IsPostBack property. That reloads all items from database and prevents this event from being triggered.
So check it:
protected bvoid Page_Load(Objject sender, EventArgs e)
{
if(!IsPostBack)
{
CreateRegionList();
}
}
That's because you have to set true to:
lstLocations.AutoPostBack = true;

ASP:Dropdownlist onselectedindexchanges function does not fire even when I set autopostback to true

I am using a wizard. and in step two the user can add information about a location that will be stored. He can add as many locations as he likes.
In step three I want to enter more information about the specific location.
To select which location to use I have ASP:dropdownlist that I populate when user enters stuff.
I want to change index but it just does not work It never goes into the function when I tried debugging. I am using a label to debug.
When I change the selected item the page reloads and the first item in the dropdown list is always selected even though I selected something else. I do not understand why that happens
here is what I have
ASPX File
Select location to enter data for:
<asp:DropDownList ID="s3_location_list" runat="server" AutoPostBack="true" OnSelectedIndexChanged="stepThree_location_list_SelectedIndexChanged">
</asp:DropDownList>
Current location index:
<asp:Label ID="Label3" runat="server" Text="Label"></asp:Label>
CS files
/*This is where I add data to the drop down list
protected void stepTwo_addLocationData(object Sender, System.EventArgs e)
{
//initialize a temporary string array to get all the data from the form
//Console.Write("AAAAA"+ Context.Items["IsRefreshed"]);
Boolean refreshed = (Boolean)Context.Items["IsRefreshed"];
if (!refreshed)
{
//if user is adding a new entry to the location table
LocationData new_location = new LocationData();
//add stuff to locationData
if (stepTwo_locationTableIndex == -1)
{
//add the new_location element into the location_data array
location_data.Add(new_location);
//redraw the table
DataRow dr = dt.NewRow();
dr["Location"] = new_location.City;
//dr["Name"] = loc;
dt.Rows.Add(dr);
}
else
{
location_data[stepTwo_locationTableIndex] = new_location;
dt.Rows[stepTwo_locationTableIndex]["Location"] = City.Text;
}
GridView1.DataSource = dt.DefaultView;
GridView1.DataBind();
///CreateTable();
stepFive_setLocationListOptions();
stepThree_setLocationListOptions();
stepTwo_resetForm();
}
/*this is the page load on step 3
protected void stepThree_load()
{
if (!IsPostBack && Session["s_s3_locationDropdownIndex"] == null)
{
stepThree_locationDropdownIndex = s3_location_list.SelectedIndex;
Session["s_s3_locationDropdownIndex"] = stepThree_locationDropdownIndex;
}
else
{
stepThree_locationDropdownIndex = (int) Session["s_s3_locationDropdownIndex"];
}
s3_location_list.SelectedIndex = stepThree_locationDropdownIndex;
Label3.Text = "" + s3_location_list.SelectedIndex;
}
/*this is my where I populate the list
protected void stepThree_setLocationListOptions()
{
s3_location_list.Items.Clear();
int i = 0;
foreach (LocationData item in location_data)
{
s3_location_list.Items.Add(new ListItem(item.City, "" + i));
}
s3_location_list.DataBind();
}
/* this is the function thats callled when selected index is changed.
protected void stepThree_location_list_SelectedIndexChanged(object sender, EventArgs e)
{
Label3.Text = "Hello";
}
I think the problem is the order of execution. You should only initialize a DropDownList once, otherwise it will overwrite your SelectedIndex. For example, use the OnInit event:
<asp:DropDownList ID="s3_location_list"
runat="server"
OnInit="s3_location_list_Init"/>
And write the event method like this:
protected void s3_location_list_Init(object sender, EventArgs e)
if (!IsPostBack) {
foreach (LocationData item in location_data)
{
s3_location_list.Items.Add(new ListItem(item.City, "" + i));
}
s3_location_list.DataBind();
}
}

CommandButton event not firing

I am populating an html table from a datatable with an edit button in each table row for each datatable row.
I am adding the edit button in code as follows:
protected void Page_Load(object sender, EventArgs e)
{
if (!Page.IsPostBack)
{
if (UserName != null && UserName != "")
{
hUserName.Value = UserName;
}
else
if (hUserName.Value != "")
UserName = hUserName.Value;
ShowTrainingEntry();
ShowUserTraining(); <-------------- this method populates table
hTID.Value = TrainingID.ToString();
}
}
public void ShowUserTraining()
{
....
dTotalTrainingHours += ShowTrainingInPeriod(dv);
....
}
protected decimal ShowTrainingInPeriod(DataView dv)
{
....
foreach (DataRowView rowView in dv)
{
....
Button bEdit = new Button();
int iTID = Convert.ToInt32(dr["ID"].ToString());
bEdit.Text = "Edit";
bEdit.ID = "btnEdit_" + iTID.ToString();
bEdit.CommandName = "Edit";
bEdit.CommandArgument = iTID.ToString();
bEdit.Command += new CommandEventHandler(btnEdit_Click);
....
}
....
}
public void btnEdit_Click(object sender, CommandEventArgs e)
{
clsLog.WriteLog("btnEdit_Click fired.");
clsLog.WriteLog("\t" + e.CommandName);
clsLog.WriteLog("\t" + e.CommandArgument.ToString());
UserName = hUserName.Value;
TrainingID = Convert.ToInt32(e.CommandArgument);
ShowTrainingEntry();
ShowUserTraining();
}
as requested - HTML table:
<asp:Table ID="tblMain" runat="server" Width="900" CellPadding="3" CellSpacing="0" CssClass="noborder">
</asp:Table>
btnEdit_Click is NOT being fired (no log entries).
I have researched this for several hours and the only thing consistent I have found is that the event must be wired to the button during Page_Load which I believe is happening correctly.
Any help would be greatly appreciated.
Thanks,
John
try to do event register
btnEdit_Click.Click += new EventHandler(this.btnEdit_Click);

how to retain the value of global string variable even after page load in asp.net

I am having problems in retaining the string variable which I defined on the top of my scoop, everytime when page loads the string value becomes null. below is the snippet of the code:
public partial class Caravan_For_Sale : System.Web.UI.Page
{
string check;
PagedDataSource pds = new PagedDataSource(); //paging
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
BindGrid();
}
}
private void BindGrid()
{
DataTable dt = null;
switch (check)
{
case "0-1500":
break;
case "1500-2000":
dt = caravans.GetFilterbyPrice1();
break;
case "2000+":
break;
default:
dt = caravans.GetAllCaravans();
break;
}
// DataTable dt = caravans.GetAllCaravans();
pds.DataSource = dt.DefaultView;
pds.AllowPaging = true;
pds.PageSize = 3;//add the page index when item exceeds 12 //Convert.ToInt16(ddlPageSize.SelectedValue);
pds.CurrentPageIndex = CurrentPage;
DataList1.RepeatColumns = 3; // 4 items per line
DataList1.RepeatDirection = RepeatDirection.Horizontal;
DataList1.DataSource = pds;
DataList1.DataBind();
lnkbtnNext.Enabled = !pds.IsLastPage;
lnkbtnPrevious.Enabled = !pds.IsFirstPage;
doPaging();
}
protected void lnkPrice2_Click(object sender, EventArgs e)
{
LinkButton _sender = (LinkButton)sender;
check = _sender.CommandArgument;
// items["test"] = test;
DataTable dt = caravans.GetFilterbyPrice2();
if (dt.Rows.Count < 3)
{
lnkbtnNext.Enabled = false;
lnkbtnPrevious.Enabled = false;
}
CurrentPage = 0;
BindGrid();
}
protected void dlPaging_ItemCommand(object source, DataListCommandEventArgs e)
{
if (e.CommandName.Equals("lnkbtnPaging"))
{
CurrentPage = Convert.ToInt16(e.CommandArgument.ToString());
BindGrid();
}
}
The string check becomes null everytime when the dlPaging_ItemCommand becomes active(page loads). Any help or suggestions will be appreciated
As far as I know, you have two options:
1) Load it again.
Not sure if it's possible in your case. This is usually done when dealing with database queries.
2) Put it in the ViewState just like this:
ViewState["check"] = check;
And load it after with this:
string check = Convert.ToString(ViewState["check"]);
Your class is instantiated on every load so it will not have a global variable from page view to page view. You will need to store it somehow. Like in the querystring or a session. You can also use the viewstate.
For example
ViewState("Variable") = "Your string"
Viewstate is the way to go, as the other people have answered. Whatever you do, please don't stuff it in the session.

Resources