Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Find Control in asp:repeater on button click event

Tags:

c#

asp.net

I have a dropdown list inside a asp:repeater item template. how can I get its value on button click event.

<asp:Repeater runat="server" ID="WorkflowListAfter" onitemcreated="WorkflowListAfterItemCreated">
    <ItemTemplate>
         <asp:DropDownList ID="ddlWorkflowMembers" runat="server" DataTextField="MemberName" DataValueField="MemberID">
    </ItemTemplate>
</asp:Repeater>

protected DropDownList ddlWorkflowMembers = new DropDownList();
protected void WorkflowListAfterItemCreated(object sender, RepeaterItemEventArgs e)
{
    ddlWorkflowMembers = (DropDownList) e.Item.FindControl("ddlWorkflowMembers");
}
protected void BtnSaveClick(object sender, EventArgs e) {
    if (ddlWorkflowMembers.SelectedItem == null) return;
}

the code above is working at first time but after postback ddlWorkflowMembers is always null expersion.

like image 299
mhesabi Avatar asked Jun 04 '12 11:06

mhesabi


1 Answers

Assuming that BtnSave is also inside the repeater.

You get the RepeaterItem by casting the button's NamingContainer. Then you can use FindControl to get the reference to your DropDownList:

protected void BtnSaveClick(object sender, EventArgs e) {
    var btn =  (Button)sender;
    var item = (RepeaterItem)btn.NamingContainer;
    var ddl =  (DropDownList) item.FindControl("ddlWorkflowMembers");
    // ...
}

If the button is outside of the repeater and you want to save all items, you need to loop through all:

protected void BtnSaveClick(object sender, EventArgs e) {
    foreach(RepeaterItem item in WorkflowListAfter.Items)
    {
        var ddl =  (DropDownList) item.FindControl("ddlWorkflowMembers");
        // ...
    }       
}
like image 51
Tim Schmelter Avatar answered Oct 18 '22 06:10

Tim Schmelter