繁体   English   中英

如何将DropDownList列添加到GridView?

[英]How to add a DropDownList column to GridView?

如何在后面的代码中将DropDownList列添加到gridview? 在我的情况下,想要添加一个名为Employer的下拉列表。 我已经使用以下代码成功添加了一个名为Name字符串列:

  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);

Name列的工作很棒,但是Employer在每行System.Web.UI.WebControls.DropDownList显示此消息。

我无法访问ASPX页面,因此无法使用TemplateField添加它

在后台代码中将DropDownList动态添加到GridView中:

protected void GridView1_RowCreated(object sender, GridViewRowEventArgs e)
{
    if (e.Row.RowType == DataControlRowType.Row)
    {
        DropDownList ddl = new DropDownList();

        ddl.AutoPostBack = true;

        // add index changed events to dropdownlists
        ddl.SelectedIndexChanged += new EventHandler(ddl_SelectedIndexChanged);

        e.Row.Cells[1].Controls.Add(ddl); // add dropdownlist to column two
    }
}

现在,已为所有GridView行创建了DropDownLists,您可以将其绑定到GridView的RowDataBound事件中。

为了遵循本文开头的先前代码,您可以按照以下更新版本进行操作,该版本应该适合您。 (再次,遵循您的语法)

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; --object being added when you need the control.
      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);

//Here is how you can add the control with the contents as needed.
    foreach (GridViewRow row in GridViewEarningLine.Rows)
    {
        drp = new DropDownList();
        drp.DataSource = list;
        drp.DataBind();
        drp.SelectedIndex = -1;
        row.Cells[1].Controls.Add(drp);
    }

您可以进行调整,因为我可能在讲解这种情况时已经犯了一个错误。

您需要查看其中的数据/值。 (对我的说法有误)

在这里它显示您需要添加控件,并且控件在其中显示数据/值。 (如果这种情况在winforms中发生,则有些不同)。

希望能有所帮助。

您在雇主中看到“ system.web ...”的原因是由于DropDownList是对象,因此您需要查看其中的数据/值。

向该列添加一些定义应该可以解决问题。

这是一个以前的工作示例,可以单独查看该列。

https://stackoverflow.com/a/14105600/2484080

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM