i have the following code
Page_Load () {
if (!IsPostBack)
{
//data binding to ddl year
} else {
if (ViewState["ddlyear"] != null)
{
ddlyear.SelectedValue = ViewState["ddlyear"].ToString();
}
}
}
ddlyear_SelectedIndexChanged {
ViewState["ddlyear"] = ddlyear.SelectedItem.Value.ToString();
}
heres the error.
-
load page select item in ddlyear, which reloads page, and correctly displays the item in the ddl.
-
if I change the displays the selected item will not change.
if I put a breakpoint on ddlyear.SelectedItem.Value.ToString(); the value actually never changes form the first call. it will change once, to the selected items value, but will not change even if another item is selected on subsequent page calls.
i.e.
- first page load – ddlyear = 1000
- change to another option, lets say 1001
- page reload, ddlyear = 1001
- change to another option, lets say 1002
- page reloads, ddlyear = 1001 not 1002
A
DropDownListwill by default maintain itsSelectedItem.You don’t need to write any code for that. Remove the code you have added and it should work just as you expect.
If you are interested in knowing why your code fails, that is because the
Loadevent fires before any event handlers are called. Here you are resetting the selected value to the one from theViewState.