c# – GridView asp.net中的DropDownList

我想为gridview中的每个条目添加一个下拉列表.

<asp:GridView ID="GridView1" runat="server"
    AutoGenerateColumns="False" 
        onselectedindexchanged="GridView1_SelectedindexChanged">

        <Columns>                
          <asp:TemplateField HeaderText="Bank">
            <ItemTemplate>
              <asp:DropDownList ID="DropDown"
                AutopostBack="true" runat="server"  DataTextField="Name" DataValueField="Name" 
              >
              </asp:DropDownList>
                </ItemTemplate>
            </asp:TemplateField>

        </Columns>
    </asp:GridView>

在后端,我有以下代码,以便将数据表绑定到该下拉列表.

DataTable reader = BusinessLayer.BusinessLayerHandler.GetBankList();
DropDown.DataSource = reader;
DropDown.DataTextField = "NAME";
DropDown.DataValueField = "NAME";
DropDown.DataBind();

我的问题是在后端找不到在网格视图(DropDown)创建的下拉列表,就好像它不存在一样.

我能做什么?

解决方法

将为GridView中的每个项目创建DropDownList,因此下拉列表中不能有一个字段.不过,您可以检索单行的DropDownList(例如,在RowDataBound或RowCreated事件中)

protected void grid_RowDataBound(object sender,GridViewRowEventArgs e)
{ 
  if(r.Row.RowType == DataControlRowType.DaTarow)
  {
    DropDownList dropdown = e.Row.FindControl("DropDown") as DropDownList;
    if(dropdown != null)
    { /*  your code */ }
  }
}

或者您可以使用DropDownList本身的事件并访问sender参数.

<asp:DropDownList ID="DropDown" OnLoad="dropdownLoad" />

protected void dropdownLoad(object sender,EventArgs e)
{ 
  DropDownList dropdown = sender as DropDownList;
  if(dropdown != null)
  { /*  your code */ }
}

相关文章

目录简介使用JS互操作使用ClipLazor库创建项目使用方法简单测...
目录简介快速入门安装 NuGet 包实体类User数据库类DbFactory...
本文实现一个简单的配置类,原理比较简单,适用于一些小型项...
C#中Description特性主要用于枚举和属性,方法比较简单,记录...
[TOC] # 原理简介 本文参考[C#/WPF/WinForm/程序实现软件开机...
目录简介获取 HTML 文档解析 HTML 文档测试补充:使用 CSS 选...