在 TemplateField 中操作 DropDownList

发布于 2024-11-10 02:50:08 字数 436 浏览 0 评论 0原文

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

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

这是我的代码:

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

I have a dropdownlist inside of a TemplateField, within a GridView.

I would like to dynamically add list items to it and write code to handle when the index changes. How do I go about manipulating the list, since I can't directly reference the DropDownList when it's in a TemplateField.

Here is my code:

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

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

终遇你 2024-11-17 02:50:08

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

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

If I'm understanding what you want to do correctly, you can handle adding items to your drop down like this:

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

Then, if you mean handling the index change of the DropDownList you just need to add an event handler to your control:

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

Then in that event handler you can use (sender as DropDownList) to get whatever you need from it:

protected void ddlTransferLocation_SelectedIndexChanged(object sender, EventArgs e)
{
    DropDownList myDropDown = (sender as DropDownList);
    if (myDropDown != null) // do something
    {
    }
}
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文