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

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

  • 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? – Nderon Hyseni Aug 16 '17 at 14:41
  • Please add the code that add the columns from code behind to can help you faster – Mohamed El-Qassas MVP Aug 16 '17 at 15:14
  • finally is working – Nderon Hyseni Aug 17 '17 at 14:31
  • But when I post I set the AutoPostBack=true the dropdown disappears, why? how to prevent it. – Nderon Hyseni Aug 18 '17 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 – Mohamed El-Qassas MVP Aug 18 '17 at 10:04

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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