我在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总是为null expersion。
答案 0 :(得分:21)
假设BtnSave
也在转发器内。
通过投射按钮NamingContainer
获得RepeaterItem
。然后,您可以使用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");
// ...
}
}