An ASP.NET Blog
I work for Microsoft and help people and businesses make better use of technolgy to realize their full potential. The opinions mentioned herein are solely mine and do not reflect those of my employer.

Handling Page Load Events and PostBack Issues

Monday, April 25, 2005 7:50 AM
A number of queries, articles from developers rise on this issue.

When you bind a dropdownlist or other databound controls to a datasource during the page_load event, the process is triggered each time the page is loaded.

In the followign code, we call a method which will populate a dropdownlist on the Page_Load Event:-

private void Page_Load(object sender, System.EventArgs e)
{
BindDropDownList1();
}

We select an item in the dropdownlist after the page has loaded and the list has been populated.

Then, we have button and on its click event, we want the selected item in the dropdownlist to be displayed.

Guess what you will get as selected item no matter what you select from the dropdownlist? The first item or the default item such as "Select an option".

The issue is due to the postback that occurs when the button is clicked. ASP.NET server controls are posted back to the server for all events and hence, the page will be reloaded - thereby the dropdownlist again populated and the selected item would be the first default item.

To avoid this, we must put the dropdownlist populating code within the IsPostBack condition, as follows:-

private void Page_Load(object sender, System.EventArgs e)
{
if(!IsPostBack)
{
BindDropDownList1();
}
}

This would ensure that the dropdownlist is not repopulated during each postback and if you try to get the selected item, you will get the correct selected item even though the page postbacks.

This is applicable to .NET version 1.0, 1.1 since in .NET 2.0 (CodeName: Whidbey), this has been handled automatically to check postbacks and normal page_loads.

Feedback

# re: Handling Page Load Events and PostBack Issues

It doesn't work however if you have a second control that is dynamically populated based on the first control. 1/15/2007 7:26 PM | DeaPeaJay

# re: Handling Page Load Events and PostBack Issues

You do not mention where the dropdown state is retrieved from when IsPostback = true. I presume it is from the View State. What if you don't want to rely on View State? 4/18/2008 4:20 AM | Bob W

# re: Handling Page Load Events and PostBack Issues

Thank you!!! 14+ years of software development and I'm now trying (with much angst and anxiety) to learn .Net. I put a couple simple pages together that seemed to work fine until I changed the dates, which caused a post back (still learning the lingo) and reset the date info...ARGH!

Your fix was clear, concise, and above all...actually worked!

Thanks again,
Shawn 5/14/2008 2:22 AM | Shawn

Post a comment





 

Please add 7 and 7 and type the answer here: