DropDownList in GridView asp.net

2019-02-25 02:13发布

问题:

I want to add a dropdownlist to every entry in a 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>

At the back end i have the following code in order to bind a datatable to that dropdown list.

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

My problem is that the drop down list created at the grid view (DropDown) is not found at the back end as if it doesn't exist..

What can I do?

回答1:

The DropDownList will be created for every single item in the GridView, so there can't be one field for the dropdownlists. Nevertheless, you can retrieve the DropDownList for a single row (e.g. in RowDataBound or RowCreated event)

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

Or you can use an event of the DropDownList itself and access the sender parameter.

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

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


回答2:

you can find dropdown into grid databound event by grid.findcontrol.