I am making a web page with asp.net, the problem has to be with a asp:datagrid and its page index changing event. The records are displaying and paging correctly but after making a filter and reduce its grid content and trigger the page index again, the grid refreshes and came back all the other records.
This is my PageLoad()
if (!IsPostBack)
{
txtDate1.Attributes.Add("placeholder", "Enter Start Date DD//MM//YY");
txtDate2.Attributes.Add("placeholder", "Enter End Date DD//MM//YY");
this.bindgrid();
}
else
this.bindgridfilter(txtDate1.Text, txtDate2.Text);
My bindGridsmethods()
private void bindgrid()
{
ds = Classes.DBMethods.ShowRecords();
grdRecords.DataSource = ds.Tables[0];
grdRecords.DataBind();
}
private void bindgridfilter(string date1, string date2)
{
dsf = Classes.DBMethods.SearchBetweenDates(date1,date2);
grdRecords.DataSource = dsf.Tables[0];
grdRecords.DataBind();
}
My PageIndexChanging Event
protected void grdRecords_PageIndexChanging(object sender, GridViewPageEventArgs e)
{
grdRecords.PageIndex = e.NewPageIndex;
grdRecords.DataBind();
}
And my FilterButton Click()
protected void Filter_Click(object sender, EventArgs e)
{
grdRecords.DataSource = null;
bindgridfilter(txtDate1.Text, txtDate2.Text);
}
Now it does the opposite it disappear the grid after making a change of page without a filter, and if it applies a filter now the pagination works correctly
2
Answers
Is it correct? PageLoad()
PageIndex Event
In most web pages, just setting up a drop down list, a grid view, or whatever?
You ONLY want to bind and load the drop down list, or gridview ONE time.
If you re-beind, and re-load the control AGAIN with data, then you will lose your settings.
So, 99% of the time, you want to do such loading ONLY one time,and ONLY on the first page load. Hence, your page load event needs to be this:
So, now when a button is clicked, or say gv selected index changes, or whatever? Then the information can be used.
If you rebind on each post back, then a gv, or even a simple drop down list will lose its values – hence ONLY load and bind your controls on first "real" page load as per above.
Page load fires EACH time and for each post back. So, any button click or whatever? The page load event will run again. Hence, your general setup code, startup code, and code to load up things like a drop down list, or gridview?
You need to have a if (!IsPostBack) code stub. The last 200 web pages I have created – everyone has such a code stub, and you really for all purposes can’t build a working web page without this "setup" or "first load" code stub. If you re-load or re-setup your controls each time, then anything the user enters or does with such controls will be lost.
Of course YOUR buttons etc. and code can and will re-load the grid, but since the page load fires every time with all and any button click (any post-back), then that re-load code will also re-fire, and you don’t want that to occur.