1

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

我想动态添加列表项并编写代码以在索引更改时进行处理。我该如何操作列表,因为当 DropDownList 位于 TemplateField 中时,我无法直接引用它。

这是我的代码:

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

1 回答 1

0

如果我理解您想要正确执行的操作,您可以像这样处理将项目添加到下拉列表中:

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
    {
    }
}
于 2011-05-26T23:18:43.320 回答