Thought I'd jot this donw - hopefully someone out there will read it and save the 15 minutes I lost to working on this little “gotcha” problem.
Scenario: You have a DataGrid with two columns. The first is a BoundColumn, the second a TemplateColumn. In the TemplateColumn you have a RadioButtonList. The idea is to have the user select precisely one option from the second column for each item in the first one. Basically, the DataGrid markup looks like:
<asp:DataGrid ...>
<Columns>
<asp:BoundColumn ... />
<asp:TemplateColumn>
<ItemTemplate>
<asp:RadioButtonList id=”radList” ... />
</ItemTemplate>
</asp:TemplateColumn>
</Columns>
</asp:DataGrid>
Now, this RadioButtonList needs to be bound to a list of options. Since the options are the same for all items in the DataGrid (and therefore not specific on the particular row), you figure that you'll use the DataGrid's ItemCreated event to do this. (FIRST MISTAKE!) The event handler looks something like:
Sub MyDataGrid_ItemCreated(...) Handles MyDataGrid.ItemCreated
If e.Item.ItemType = ... Then
'Get a reference to the RadioButtonList
Dim radList as RadioButtonList = CType(...)
'Bind the data
radList.DataSource = ...
radList.DataBind()
End If
End Sub
The above will work just fine, although it is a bit inefficient (more on that later). Now, if you were to see the DataGrid, you'd see a series of rows with the second column in each row with a set of radio buttons. However, no radio button is selected by default. Ok, easy enough, go and add radList.SelectedIndex = 0 right after the radList.DataBind() call, right? Well, you'd think that work, but it doesn't. No error, of course, just no selected radio button.
Now, if you are like me, you spend the next 15 minutes thinking about this, opening Reflector, reading the docs, and being generally unproductive.
If you want to waste less time, you would simply move this code to the ItemDataBound event rather than ItemCreated. After ItemCreated, the DataGrid assigns the DataSource record to the DataItem property of the current DataGridItem (e.Item) and then calls the DataBind() method of that DataGridItem. The DataGridItem propogates the DataBind() call down to its child controls, meaning the RadioButtonList will have its OnDataBinding event fire. What happens there? Well, it sees that the DataSource for the RadioButtonList is not null, so it clears out the RadioButtonList items, and rebinds the data! This, of course, has the negative side-effect of clearing out the SelectedIndex setting.
Solution: anytime you find yourself calling DataBind() for a Web control that exists in a TemplateColumn of the DataGrid, make sure you are doing so in the DataGrid's ItemDataBound event, otherwise the data will be bound twice to the Web control, which will not only be less efficient, but might have negative side-effects, as seen here.