Paging Selected Index Causes DataGrid Refresh - c#

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

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:
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
txtDate1.Attributes.Add("placeholder", "Enter Start Date DD//MM//YY");
txtDate2.Attributes.Add("placeholder", "Enter End Date DD//MM//YY");
bindgrid();
}
}
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.

Is it correct? PageLoad()
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
txtDate1.Attributes.Add("placeholder", "Enter Start Date DD//MM//YY");
txtDate2.Attributes.Add("placeholder", "Enter End Date DD//MM//YY");
this.bindgrid();
}
}
PageIndex Event
protected void grdRecords_PageIndexChanging1(object sender, GridViewPageEventArgs e)
{
grdRecords.PageIndex = e.NewPageIndex;
if (txtDate1.Text == "" & txtDate2.Text == "")
{
bindgrid();
}
else
this.bindgridfilter(txtDate1.Text, txtDate2.Text);
}

Related

Remove Session Value If I Delete Value From Field And Re-Submit Form

I have an asp.net webform that stores details entered in the session and then displays all the details on a confirmation page later on. All these works are fine.
If the user navigates back to the page, the details are still displayed but the issue i'm having is that:
User Scenario
User enter's details in a none mandatory field and continues. This value is displayed on the confirmation page as expected. User then goes back to the page and deletes the value in the none mandatory field and continues BUT the value deleted is still deleted on my confirmation page.
I have debugged it and at first I can see that the field is empty. But when the code drops back into my submitbutton_click, it re-adds it.
The current code that I have is displayed below:
Code
protected void Page_Load(object sender, EventArgs e)
{
if (Step01AddressBuildingname.Text == string.Empty && Session["Step01AddressBuildingname"] != null)
{
Step01AddressBuildingname.Text = Session["Step01AddressBuildingname"].ToString();
}
}
protected void Step01SubmitButton_Click(object sender, EventArgs e)
{
Session["Step01AddressBuildingname"] = Step01AddressBuildingname.Text;
}
From what I can discern from your post it seems that when you update the Step01AddressBuildingname field to be blank and click on submit, this does not clear down the session value as expected. If so it's because you're not handling the post back in you page_load event. In asp.net webforms postbacks occur when a form is submitted to the server, in this scenario you just want to handle the form submission and not load the page as standard. You do this by checking the IsPostBack property on the page.
In your code, because you're not checking this property, tep01AddressBuildingname.Text = Session["Step01AddressBuildingname"].ToString(); is getting executed before the submit button's click event handler - hence the value doesn't get deleted. Try this
protected void Page_Load(object sender, EventArgs e)
{
if (!Page.IsPostBack) {
if (Step01AddressBuildingname.Text == string.Empty && Session["Step01AddressBuildingname"] != null)
{
Step01AddressBuildingname.Text = Session["Step01AddressBuildingname"].ToString();
}
}
}
protected void Step01SubmitButton_Click(object sender, EventArgs e)
{
Session["Step01AddressBuildingname"] = Step01AddressBuildingname.Text;
}

How can I trigger dropdown while viewing asp.net page

There are two Dropdown in the asp.net page.
When I select first one (city), the second one (district) is triggered.
I have a save button for the page.
When I click the save button, I write the SelectedValues of dropdowns in to the database.
And when I open the page again, I assign the values to the dropdown's selected values.
The first one is ok when I assign dropdown.SelectedValue = "5" but the second one is not triggered. How can I trigger it?
Thanx.
I have done the same thing. Suppose you have drop down say ddlCountry and ddlCity. You need to load all cities just for the selected country.
protected void Page_Load(object sender, EventArgs e)
{
if(!IsPostBack)
{
LoadCountriesInDropDown(ddlCountry);
ddlCountry.SelectedValue = "5" //For eg:
LoadCitiesByCountrySelected(ddlCity, ddlCountry.SelectedValue); // selected country value was set here as 5
ddlCountry_SelectedIndexChanged(null, null);
}
}
protected void ddlCountry_SelectedIndexChanged(object sender, EventArgs e)
{
if(ddlCountry.SelectedItem.Text == "Select")
{
ddlCity.Items.Clear();
}
else
{
LoadCitiesByCountrySelected(ddlCity, ddlCountry.SelectedValue);
}
}
Hope this was what you wanted.

Save selected value of a dropdown list in a global variable

I am trying to save the dropdown list selected value in a glbal variable .. I have lots of country on the dropdown list , whan I choose one of them and press a button :
protected void Button1_Click(object sender, EventArgs e)
{
Button2.Enabled = true;
Button2.Visible = true;
DropDownList1.Visible = true;
DropDownList9.Items.Clear();
if (!Class1.Search_Continent.Equals("-"))
{
SqlConnection conn1 = new SqlConnection(#"Data Source=AK-PC\MSSQLSERVER1;Initial Catalog=DB;Integrated Security=True");
conn1.Open();
SqlCommand cmd1 = new SqlCommand("Select Country_name FROM Country WHERE Continent_name='" + DropDownList1.SelectedValue + "'", conn1);
SqlDataReader dr1;
dr1 = cmd1.ExecuteReader();
while (dr1.Read())
{ DropDownList9.Items.Add(dr1["Country_name"].ToString() + "\n"); }
dr1.Close();
conn1.Close();
}
protected void Button2_Click(object sender, EventArgs e)
{
// Redirect to Country page
Class1.CountryName = DropDownList9.SelectedValue.ToString();
Response.Redirect("Country.aspx", true);
}
it doesnt take the selected value ! it always take the first value of the dropdown list !
Please help me !
You are probably re-binding the DropDownList9 on postback and losing the SelectedValue.
protected void Page_Load(object sender, EventArgs e)
{
if(!Page.IsPostback)
{
//bind data
}
}
it always take the first value of the dropdown list
This is very common in web forms if you're populating the data incorrectly. Where are you populating the drop down list? I'm going to guess that you're doing it in Page_Load. I'm also going to guess that you don't have it wrapped in something like if (!IsPostBack). If you put a debugging breakpoint in Page_Load you'll find that it's called in the post-back before Button2_Click is called.
Keep in mind that HTTP is stateless. This means that the entire server-side page object needs to be constructed on each request to the server. Page_Load is part of that construction, and it happens before event handlers do. So what's likely happening is:
User requests initial page.
You populate the drop down list with data.
You display the page to the user.
User selects an option and clicks a button, making a post-back request.
You clobber and re-populate the drop down list, returning it to a default state.
You try to get the selected value, which is now gone.
The most common solution to this problem is to use the aforementioned conditional in Page_Load:
protected void Page_Load(object sender, EventArgs e)
{
// some initial logic
if (!IsPostBack)
{
// stuff that should only happen when the page first loads
// for example, populating controls from the database
}
// any other logic, etc.
}
The values for the controls shouldn't need to be re-populated with each postback because things like viewstate should keep the necessary data available. (Though if you mess with that at all then you might need to tinker some more.)

How to Refresh GridView after closing down Dialog in ASP .NET

I have a main page with a Gridview that shows data from a Database. In the gridview there is a button, when this button is clicked a Dialog will appear allowing u to edit the selected row. The dialog is created as an aspx class. When i edit the data and close down the dialog i want to refresh my GridView on the Main page so the edited data is represented. How can i do this?
my code for editing the data and closing down the dialog is this:
protected void editButton_Click(object sender, EventArgs e)
{
string alias = Request.QueryString["alias"];
string custid = Request.QueryString["custid"];
controller.EditDeliveries(custid, alias, tdaysField.Text, thoursField.Text, ttypeField.Text, pdaysField.Text, phoursField.Text, ptypeField.Text);
ClientScript.RegisterClientScriptBlock(GetType(), "onUpload", "<script type='text/javascript'> window.close();</script>");
}
Can anyone help ?
And if u need to see more code please tell me.
Just set your datasource again and rebind it in the postback
gvMyGrid.DataSource = myData; //Fresh from the database
gvMyGrid.DataBind(); //Bam, fresh data
Edit: Oh and if it's another Control that is the source of the postback, you can use a Bubble Event to trigger the refresh.
Second Edit: To have the Dialog Page tell the Main Page to update that grid:
RaiseBubbleEvent(this, new CommandEventArgs("DataUpdated", "This could be null, or I could be a message to let the user know things are updated"));
Then on your main Page
protected override bool OnBubbleEvent(object sender, EventArgs e)
{
if (e is CommandEventArgs)
{
var args = (CommandEventArgs)e;
//Could use args.CommandArgument here
switch(args.CommandName)
{
case "DataUpdated":
gvMyGrid.DataSource = myData;
gvMyGrid.DataBind();
return true; //Handled the event LIKE A BOSS
}
}
return false; //I didn't handle this event
}

Only add items to a dropdown list once

I have a dropdown list that is populated when the page loads, like this:
protected void Page_Load(object sender, EventArgs e)
{
ddlCars.Items.Add("Ford");
ddlCars.Items.Add("Chevy");
ddlCars.Items.Add("BMW");
ddlCars.Items.Add("Jeep");
ddlCars.Items.Add("Nissan");
}
It works fine, but when a user changes the selection of the dropdown list, the list is repopulated and I see the same items twice, because the page is reloading and these values are being re-added.
What would be the best way to stop this from happening? It is important that AutoPostBack stays enabled, so that I change information based on user selection.
Thanks
You need to put that code in a !Page.IsPostBack block.
protected void Page_Load(object sender, EventArgs e)
{
if (!Page.IsPostBack)
{
ddlCars.Items.Add("Ford");
ddlCars.Items.Add("Chevy");
ddlCars.Items.Add("BMW");
ddlCars.Items.Add("Jeep");
ddlCars.Items.Add("Nissan");
}
}
This will allow that code to run once (when the page loads the first time), and then be ignored whenever the page is posting back to the server due to user interaction, etc.
For more information, see Page.IsPostBack on MSDN.
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack) {
ddlCars.Items.Add("Ford");
ddlCars.Items.Add("Chevy");
ddlCars.Items.Add("BMW");
ddlCars.Items.Add("Jeep");
ddlCars.Items.Add("Nissan");
//ddlCars.datasource=?
//ddlCars.databind();
}
}

Categories