dgamma3
dgamma3

Reputation: 2371

drop down list not updating selected item on subsequent calls

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.

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.

  1. first page load - ddlyear = 1000
  2. change to another option, lets say 1001
  3. page reload, ddlyear = 1001
  4. change to another option, lets say 1002
  5. page reloads, ddlyear = 1001 not 1002

Upvotes: 0

Views: 1308

Answers (1)

nunespascal
nunespascal

Reputation: 17724

A DropDownList will by default maintain its SelectedItem.
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 Load event fires before any event handlers are called. Here you are resetting the selected value to the one from the ViewState.

Upvotes: 1

Related Questions