在TemplateField中操作DropDownList

本文关键字:DropDownList 操作 TemplateField | 更新日期: 2023-09-27 17:57:41

我在GridView中的TemplateField中有一个下拉列表。

我想动态地向其中添加列表项,并编写代码来处理索引何时更改。我该如何操作列表,因为当DropDownList在TemplateField中时,我不能直接引用它。

这是我的代码:

<asp:TemplateField HeaderText="Transfer Location" Visible="false">
   <EditItemTemplate>
      <asp:DropDownList ID="ddlTransferLocation" runat="server" ></asp:DropDownList>
   </EditItemTemplate>
 </asp:TemplateField>

在TemplateField中操作DropDownList

如果我理解你想要正确地做什么,你可以像这样处理向下拉列表中添加项目:

foreach (GridViewRow currentRow in gvMyGrid.Rows)
{
    DropDownList myDropDown = (currentRow.FindControl("ddlTransferLocation") as DropDownList);
    if (myDropDown != null)
    {
        myDropDown.Items.Add(new ListItem("some text", "a value"));
    }
}

然后,如果你想处理DropDownList的索引更改,你只需要在控件中添加一个事件处理程序:

<asp:DropDownList ID="ddlTransferLocation" runat="server" OnSelectedIndexChanged="ddlTransferLocation_SelectedIndexChanged" AutoPostBack="true"></asp:DropDownList>

然后,在该事件处理程序中,您可以使用(sender as DropDownList)从中获得所需的一切:

protected void ddlTransferLocation_SelectedIndexChanged(object sender, EventArgs e)
{
    DropDownList myDropDown = (sender as DropDownList);
    if (myDropDown != null) // do something
    {
    }
}