2

How can I add a DropDownList column to gridview in code behind? In my case a want to add a dropdown called Employer. I have successfully added 1 string column called Name with the following code:

  DataTable dt = new DataTable();
  DropDownList drp = new DropDownList();

  dt.Columns.Add("Name", typeof(string));
  dt.Columns.Add("Employer", typeof(DropDownList));

  drp.Items.Add(new ListItem("test", "0"));

  foreach (SPListItem item in queryResults)
  {

      dr["Name"] = item["iv3h"].ToString();
      dr["Employer"] = drp;
      dt.Rows.Add(dr);
  }

   BoundField bf = new BoundField();
   bf.DataField = "Name";
   bf.HeaderText = "Name";
   bf.HeaderStyle.HorizontalAlign = HorizontalAlign.Left;
   bf.ItemStyle.HorizontalAlign = HorizontalAlign.Left;
   GridViewEarningLine.Columns.Add(bf);

The Name column is working wonderful but the Employer is showing this message in each row System.Web.UI.WebControls.DropDownList.

I DON'T HAVE ACCESS TO ASPX PAGE SO I CANNOT ADD IT WITH TemplateField

1 Answer 1

4

First, Visual Web Part has a code behind so you can add ASP.Net control like Gridview and add your dropdown list control to a template field as shown below

<asp:GridView ID="GridView" runat="server" onrowdatabound="GridView_RowDataBound">
      <Columns>
          <asp:TemplateField>
              <ItemTemplate>
                 <asp:DropDownList ID="ddl" runat="server">
                 </asp:DropDownList>
              </ItemTemplate>
          </asp:TemplateField>
      </Columns>
  </asp:GridView>

Second, you will need to bind the dropdown list in RowDataBound as shown below

   protected void GridView_RowDataBound(object sender, GridViewRowEventArgs e)
    {

        if (e.Row.RowType == DataControlRowType.DataRow)
        {
            DropDownList dropcontrol = (DropDownList)e.Row.FindControl("ddl");
             foreach (SPListItem item in queryResults)
                dropcontrol .Items.Add( item["columnName"].ToString());
        }
    }

Regarding ordering check How to reorder columns in grid-view dynamically

5
  • But due that all columns are are added with code behind if I do this the dropdown will be displayed in the first column. How can i reorder columns because I want this dropdown to be in the last column? Commented Aug 16, 2017 at 14:41
  • Please add the code that add the columns from code behind to can help you faster Commented Aug 16, 2017 at 15:14
  • finally is working Commented Aug 17, 2017 at 14:31
  • But when I post I set the AutoPostBack=true the dropdown disappears, why? how to prevent it. Commented Aug 18, 2017 at 7:23
  • do you have any event in the dropdown list? if no no need for post back if yes try to use update panel Commented Aug 18, 2017 at 10:04

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.