I have a gridview in which every row contains a dropdownlist. I want to bind every dropdownlist dynamically. Can someone tell me how can i do it. Thanks in Advance
            Asked
            
        
        
            Active
            
        
            Viewed 9.0k times
        
    5 Answers
19
            If you are using template column then you can bind your drop-down from mark-up using data-binding expressions. For example,
<asp:TemplateField HeaderText="XYZ">
  <ItemTemplate>
    <asp:DropDownList runat="server" ID="MyDD" DataSourceId="MyDataSource" />
  </ItemTemplate> 
</asp:TemplateField>
Above is assuming that your drop-down data in constant across rows. If it is changing then you can use data-binding expression such as
<asp:DropDownList runat="server" DataSource='<%# GetDropDownData(Container) %>' DataTextField="Text" DataValueField="Value"  />
GetDropDownData will be a protected method in code-behind that will return the data (data-table, list, array) for the given row.
You can use GridView.RowDataBound event (or RowCreated event) in code-behind to fill drop-downs. For example,
  protected void GridView_RowDataBound(Object sender, GridViewRowEventArgs e)
  {
    if(e.Row.RowType == DataControlRowType.DataRow)
    {
      // Find the drop-down (say in 3rd column)
      var dd = e.Row.Cells[2].Controls[0] as DropDownList;
      if (null != dd) {
         // bind it
      }
      /*
      // In case of template fields, use FindControl
      dd = e.Row.Cells[2].FindControl("MyDD") as DropDownList;
      */
    }
  }
 
    
    
        VinayC
        
- 47,395
- 5
- 59
- 72
- 
                    What about the RowCreated event? Would there be a reason to prefer one over the other? – Tim Sep 07 '11 at 05:31
- 
                    @Tim, RowCreated will also work. However, I believe that if you are binding the grid only first time (and not on post-back), `RowCreated` will certainly fire on every post-back but not `RowDataBound` (I am not 100% sure here). So in such case, we can rely on view-state to get drop-down to filled up. Personally, I prefer markup route. – VinayC Sep 07 '11 at 05:47
- 
                    1This is assumed that you have your SQL instance declared in your code. If you already bound your grid view in your code behind then there needs to be a different solution, because you would not be able to use DataSourceId="MyDataSource" – Coded Container Sep 19 '17 at 15:46
16
            
            
        In addition to the proposed methods, you may also bind your controls within your markup, in this way:
<asp:GridView ID="MyGrid" runat="server" DataSourceID="MyDataSource1">
    <Columns>
        <asp:TemplateField>
            <EditItemTemplate>
                <asp:DropDownList ID="DropDownList1" runat="server" SelectedValue='<%# Bind ("CustomerId") %>' DataSourceID="CustomersDataSource" DataTextField="CustomerName" DataValueField="CustomerId" >
                </asp:DropDownList>
            </EditItemTemplate>
        </asp:TemplateField>
    </Columns>
</asp:GridView>
 
    
    
        Efran Cobisi
        
- 6,138
- 22
- 22
- 
                    Can you show how this would update and display in the label of the ItemTemplate? – htm11h Nov 17 '14 at 19:42
1
            
            
        Here is your gridview
<asp:GridView ID="grvExcelData" runat="server" onrowdatabound="GridView2_RowDataBound">
    <HeaderStyle BackColor="#df5015" Font-Bold="true" ForeColor="White" />
      <Columns>
          <asp:TemplateField>
              <ItemTemplate>
                 <asp:DropDownList ID="DrdDatabase" Width="100px" runat="server">
                 </asp:DropDownList>
              </ItemTemplate>
          </asp:TemplateField>
      </Columns>
  </asp:GridView>
and your RowDataBound event for the gridview would be
    protected void GridView2_RowDataBound(object sender, GridViewRowEventArgs e)
    {
       string cities = "maxico,chennai,newdelhi,hongkong";
       string [] arr = cities.Split(',');
    // Instead of string array it could be your data retrieved from database.
        if (e.Row.RowType == DataControlRowType.DataRow)
        {
            DropDownList ddl = (DropDownList)e.Row.FindControl("DrdDatabase");
            foreach (string colName in arr )
                ddl.Items.Add(new ListItem(colName));
        }
    }
 
    
    
        Chandan Kumar
        
- 4,570
- 4
- 42
- 62
- 
                    This does not look like this is bound to a database but instead attached to an array of cities. If a user makes a change to the drop-down how will this update the database? – Coded Container Sep 19 '17 at 15:44
-1
            
            
        protected void gvSalesAppData_RowDataBound(Object sender, GridViewRowEventArgs e)
    {
        if (e.Row.RowType == DataControlRowType.DataRow)
        {
            DropDownList ddlCurrentPhase = (DropDownList)e.Row.FindControl("ddlCurrentPhase");
            DropDownList ddlProductFamily = (DropDownList)e.Row.FindControl("ddlProductFamily");
            DropDownList ddlProductGroup = (DropDownList)e.Row.FindControl("ddlProductGroup");
            DropDownList ddlETProgramManager = (DropDownList)e.Row.FindControl("ddlETProgramManager");
            DropDownList ddlPLMForTheProduct = (DropDownList)e.Row.FindControl("ddlPLMForTheProduct");
            TrackingToolObj.BindCurrentPhases(ddlCurrentPhase);
            TrackingToolObj.BindCurrentPhases(ddlProductFamily);
            TrackingToolObj.BindProductGroups(ddlProductGroup);
            TrackingToolObj.GetEmployeesBasedOnRoleTypeId(ddlETProgramManager, (int)OSAEnums.RoleTypes.ProgramManager, false);
            TrackingToolObj.GetEmployeesBasedOnRoleTypeId(ddlPLMForTheProduct, (int)OSAEnums.RoleTypes.PLM, false);
        }
    }
 
    
    
        Baby Groot
        
- 4,637
- 39
- 52
- 71
-2
            
            
        Binding the GridView
Below is the code to Bind the GridView control with data.
C#
protected void Page_Load(object sender, EventArgs e)
{
   if (!IsPostBack) 
   {
     this.BindData();   
   }
} 
private void BindData()
{
   string query = "SELECT top 10 * FROM Customers";    
   SqlCommand cmd = new SqlCommand(query);    
   gvCustomers.DataSource = GetData(cmd);    
   gvCustomers.DataBind(); 
}
private DataTable GetData(SqlCommand cmd)
{    
    string strConnString = ConfigurationManager.ConnectionStrings["conString"].ConnectionString;    
    using (SqlConnection con = new SqlConnection(strConnString))   
    {        
       using (SqlDataAdapter sda = new SqlDataAdapter())     
       {            
          cmd.Connection = con;            
          sda.SelectCommand = cmd;            
          using (DataTable dt = new DataTable())  
          {                
              sda.Fill(dt);                
              return dt;
          }     
       }   
    }
}
- 
                    
- 
                    2To be honest, that's a daft way of doing it. If you have 500 rows in a gridview, you are going to query a database 500 times? When I have to do this, I fill a dataset with the data for the items in the drop down list and, as shown above, in the RowDataBound event, bind the DataSet to the dropdownlist(s). – Martin Smellworse Oct 14 '13 at 09:50
 
     
     
    