在asp.net中,GridView中的下拉列表框

3
我想在网格视图的每个条目中添加一个下拉列表。
    <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();

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

我该怎么办?

2个回答

8

DropDownList将为GridView中的每个项目创建,因此不能为下拉列表设置一个字段。尽管如此,您可以检索单个行的DropDownList(例如在RowDataBoundRowCreated事件中)。

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 */ }
}

首先,您需要检查您正在处理的行的类型。在尝试查找下拉列表之前,如果(e.Row.RowType == DataControlRowType.DataRow) - Henry
不是必须的,但应该做,没错...我刚刚编辑了我的回答。 - Stephan Bauer

-1

你可以通过 grid.findcontrolgrid databound event 中找到 dropdown


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接