Question

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

Était-ce utile?

La solution

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

Licencié sous: CC-BY-SA avec attribution
Non affilié à sharepoint.stackexchange
scroll top