Have you ever tried to set the SelectedIndex property of a DataList programmatically, so that the SelectedItemTemplate will be used? For example, you might be binding to the DataList information about products, and you might want to have the cheapest or most expensive product “selected” so that it is rendered via the SelectedItemTemplate. Initially, you might think to solve this problem by creating an event handler for the DataList's ItemDataBound event, and then to programmatically set the SelectedIndex property based on the index of the row that meets whatever criteria you have outlined to be “selected.”
Sadly, this approach won't work due to the order of events in rendering a DataList. Let's step through the series of events that transpire when the DataList's DataBind() method is called. For each item in the DataList's DataSource, the following things happen in this order:
- A DataListItem instance is created.
- The proper template is used to render the contents of the DataListItem. It's at this point that the DataList's
SelectedIndex is checked to see whether the ItemTemplate should be used or if the SelectedItemTemplate should be used.
- The DataList's
ItemCreated event is raised.
- The DataListItem's
DataItem property is set to the current DataSource row, and the DataListItem's DataBind() method is called.
- The DataList's
ItemDataBound event is raised.
By examining the above sequence of events, it hopefully is evident why we can't simply set the SelectedIndex property in the DataList's ItemDataBound event and have it work as planned. The reason is because the SelectedItemTemplate has already been applied several steps before the DataList's ItemDataBound event fires. So, if setting the SelectedIndex in the ItemDataBound event handler is too late, where can we set this property?
The answer is that you have to set it before calling the DataBind() method. Namely, after getting your data from the database but before calling the DataList's DataBind() method, you have to iterate through the records and determine the record index of the record that is to be selected. Then, you have to set this property, and only then can you call DataBind(). This approach solves the problem discussed previously because it sets the SelectedIndex property before any of the five steps transpire.
If you want to learn more, check out the in-depth FAQ I wrote on this topic: Setting the SelectedIndex Programmatically.
Happy Programming!