C# – Assign an event to a custom control inside a Repeater control

asp.netc

I have a Repeater control which in some of its cells contains a UserControl which contains a DropDownList. On the ItemDataBound event of the Repeater control I'm assigning an event to the DropDownList like so:

protected void MyRepeater_ItemDataBound(object sender, RepeaterItemEventArgs e)  
{  
...  
MyControl myControl = (MyControl)e.Item.FindControl("MyControl01");  
myControl.DataSource = myObject;  
myControl.DataBind();  
myControl.DropDownList.SelectedItemChange += MyMethod_SelectedIndexChanged;  
myControl.DropDownList.AutoPostBack = true;  
....  
}  

protected void MyMethod_SelectedIndexChanged(object sender, EventArgs e)  
{  
//Do something.  
}

The event never fires. Please I need help.

Best Answer

Your event is not being raised in a PostBack because your event handler has not been attached (it is only attached during the iteration of the page life-cycle when your repeater is databound).

If you attach your event handler declaratively in the markup such as:

<asp:Repeater ID="Repeater1" runat="server">
     <ItemTemplate>
         <asp:DropDownList ID="DropDownList1" runat="server" OnSelectedIndexChanged="DropDownList1_SelectedIndexChanged" />
    </ItemTemplate>
</asp:Repeater>

Then your event handler will be called during PostBacks.

Related Topic