【问题标题】:Manipulating DropDownList within TemplateField在 TemplateField 中操作 DropDownList
【发布时间】:2011-05-26 18:51:45
【问题描述】:

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

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

这是我的代码:

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

【问题讨论】:

  • 为什么不能直接引用DropDown? myGrid.Rows[index].FindControl("ddlTransferLocation") 作为 DropDownList。如果您使用它,可以从 GridView.SelectedIndex 找到索引。此外,一些每行 GridView EventArgs 暴露了触发事件的行(e.RowIndex,其中 e 是 GridView*EventArgs)
  • 另外,您想“编写代码以在索引更改时进行处理”。你指的是哪个索引,GridView 还是每个 DropDownList?

标签: c# asp.net gridview drop-down-menu templatefield


【解决方案1】:

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

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

【讨论】:

  • 这就是我要找的,谢谢!不过,还有一个问题,当您更改为特定的下拉字段时,我的方法使模板字段可见。但是,它将下拉选择的索引重置回 0。有没有办法让它不重置选定的索引?
  • 问题是动态添加的东西没有被持久化在 ViewState 或 ControlState 中。真正正确的处理方法是编写一个自定义控件,扩展 GridView 以处理添加的状态问题。我正在为您开发一种快速修复类型的解决方案
  • 由于状态的原因,这实际上非常讨厌。没有快速简便的解决方案。您是否需要它来做任何服务器端的事情,或者您是否可以只使用一些 jQuery 来添加下拉项以及基于下拉选择的其他字段的切换可见性?如果能得到你需要的东西,它可能会容易得多(实际上是更好的用户体验)。
  • 如果客户端编程更简单,我不会反对它。不过,我以前从未真正混合过 javascript 和 ASP.NET。
猜你喜欢
  • 1970-01-01
  • 2017-01-12
  • 1970-01-01
  • 1970-01-01
  • 2018-07-23
  • 2014-07-18
  • 2010-12-11
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多