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.