Disclaimer The opinions expressed herein are my own personal opinions and do not represent my employer's view in any way.
DropDownLists within a Repeater appear to lose or forget which item is selected before the page loads. This is not the case. Dynamically created DropDownLists inside of a Repeater create a rare obstacle. The SelectedItem is not being lost or forgotten. It only appears that way because the OnDataBinding event for the DropDownList is being called twice. Only when the RepeaterItem containing the DropDownList calls its own DataBind method is the data actually bound to the DropDownList. Consider the following code:
// UsingDropDownLists.aspx115 <asp:Repeater id="rptOne" runat="server" OnItemCreated="rptOne_ItemCreated"/>116 <ItemTemplate>117 <asp:Literal id="litQuestion" runat="server"/>118 <asp:DropDownList id="ddlResponse" runat="server"/>119 <br/>120 </ItemTemplate>121 </asp:Repeater>// UsingDropDownLists.aspx.cs211 protected void rptOne_ItemCreated(object sender, RepeaterItemEventArgs e)212 {213 if(e.Item.DataItem != null)214 { 215 MyClass myClass = sender as MyClass;216 (e.Item.FindControl("litQuestion") as Literal).Text = myClass.Question;217 DropDownList ddl = e.Item.FindControl("ddlResponse") as DropDownList;218 ddl.DataSource = GetResponseList(myClass.AvailableResponses);219 ddl.Items.FindByValue(myClass.Response).Selected = true;220 ddl.DataBind();221 ddl.SelectedIndex = e.Item.ItemIndex%(ddl.Items.Count-1); //Random222 }223 }
RepeaterItem inherits from Control. If you look at Control's DataBind() method in Lutz Roeder's .NET Reflector, you will see that it performs a DataBind on each of its child controls.
public virtual void DataBind(){ this.OnDataBinding(EventArgs.Empty); if (this._controls != null) { string text1 = this._controls.SetCollectionReadOnly("Parent_collections_readonly"); int num1 = this._controls.Count; for (int num2 = 0; num2 < num1; num2++) { this._controls[num2].DataBind(); } this._controls.SetCollectionReadOnly(text1); }}
From this, we can see three things.