DropDownList in GridView asp.net

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?

Answers:

Thank you for visiting the Q&A section on Magenaut. Please note that all the answers may not help you solve the issue immediately. So please treat them as advisements. If you found the post helpful (or not), leave a comment & I’ll get back to you as soon as possible.

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

Method 2

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


All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0

0 0 votes
Article Rating
Subscribe
Notify of
guest

0 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
0
Would love your thoughts, please comment.x
()
x