I encountered a quirk today with pre-selecting a list item in the code-behind for a data-bound dropdown list during both the Page.Load and Page.PreRender events.
I could set the selected value, but I could not check the list to see if the value that I wanted to select is actually available for selection. This is important in case there is bad data in the database… instead of having the page break I want the dropdown list to default to the first selectable option (or output a detailed error message depending on what makes the most sense).
The page I was working on was a report that had a GridView control presenting the data, and had two bound dropdown lists that the user could use to filter the presented report. On the first load of the page I wanted to set the default selections in the dropdown lists based on the user’s geographic location.
The check I wanted to do seemed rather simple at first:
Dim liDept As ListItem = ddlDepartment.Items.FindByValue("1") If Not liDept Is Nothing Then ddlDepartment.SelectedValue = "1" End If
However, to my surprise the lists were not being defaulted correctly since the ListItem liDept was coming back as ‘Nothing’. Wow, what?
Anyway, after a bit of playing around it was clear that both the Page.Load and Page.PreRender events were too early to do the check. I was surprised by this since if I did not check the list of items, but just set the SelectedValue in either Page event, then the dropdown list option I was specifying would be properly selected.
It turns out that the correct event to use to manipulate a dropdown list is in the DataBound event of the control. Now that I think back on it, this makes perfect sense. But for a little while it had me wondering what was going on, especially since the selected value could be set but the list of items could not be accessed.
It seems that .NET will allow the programmer to set a selected value more or less anywhere, and that this will be remembered by the code until the control is rendered at which time the selection actually takes place. However checking the items in the list is more picky since the list is only populated at a specific point in time.
Sometimes the ASP.NET Page life cycle can be confusing, as this example with dropdownlists illustrates. I intend to write posts on the various Page life cycle events in the near future in the hopes that this will help illustrate the various stages of the Page life cycle, and what events to use for specific control manipulations.