ASP.NET C#, need to press a button twice to make something happen
To be very clear. The button click event happens after the Page_Load event meaning that the filtering does not get applied on the first postback. It has been updated on the second postback and you see the filtering. The simplest change to get your code to work is to move all the code in your Page_Load event into OnPreRender so the reload happens after the button click event.
A cleaner solution however is probably to move it into a LoadData function and call that on PageLoad when it is not a postback and also call it on the button click event after updating your filters. That will prevent a call to the database on any postback page cycles that do not need to reload the data:
protected void Page_Load(object sender, EventArgs e)
{
if (!Page.IsPostBack)
{
LoadData()
}
}
private void LoadData()
{
labDownloadList.Text = null;
//Session variables:
if (Session["Game"] != null)
...
}
protected void btnFilter_Click(object sender, EventArgs e)
{
game = lstGames.SelectedValue;
modtype = lstTypeMod.SelectedValue;
filter = true;
LoadData();
}
A last piece of quick advice for a budding ASP.Net developer is to thoroughly learn the page lifecycle. Knowing the sequence of events on a page is essential. Good Luck.
I'm not seeing the typical
if (!Page.IsPostBack)
{
...
}
in your Page_Load method, which means that your datbinding will occur every time the page is loaded, most likely causing your issue. I'd suggest adding that to the code and see if it resolves the issue.
Microsoft's overview of the Page Life Cycle may be helpful in understanding the flow (and resolving your issue).
The button click event handlers happen AFTER Page_Load. Try using Page_LoadComplete instead.
So, in your code, once the button is clicked, the page_load event fires and sets the data, then the btnClick event fires and changes the data. But, the data was already bound in it's old form. That's why it takes 2 clicks for it to work.
If you put the same page_load code into the page_loadcomplete event instead, it will happen after the btnClick event. That should produce the desired result.