11

我在 asp:repeater 项目模板中有一个下拉列表。如何在按钮单击事件中获取其值。

<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;
}

上面的代码第一次工作,但回发后 ddlWorkflowMembers 总是空 expersion。

4

1 回答 1

23

假设它BtnSave也在中继器内部。

您可以RepeaterItem通过投射按钮的NamingContainer. 然后您可以使用FindControl来获取对您的引用DropDownList

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

如果按钮在中继器之外,并且您想保存所有项目,则需要遍历所有:

protected void BtnSaveClick(object sender, EventArgs e) {
    foreach(RepeaterItem item in WorkflowListAfter.Items)
    {
        var ddl =  (DropDownList) item.FindControl("ddlWorkflowMembers");
        // ...
    }       
}
于 2012-06-04T11:18:24.723 回答