C# 如何将DropDownList列添加到GridView?
如何将C# 如何将DropDownList列添加到GridView?,c#,asp.net,gridview,C#,Asp.net,Gridview,如何将DropDownList列添加到代码隐藏中的gridview?在我的例子中,a希望添加一个名为Employer的下拉列表。我已成功添加了一个名为Name的字符串列,代码如下: DataTable dt = new DataTable(); DropDownList drp = new DropDownList(); dt.Columns.Add("Name", typeof(string)); dt.Columns.Add("Employer", typeof(DropD
DropDownList
列添加到代码隐藏中的gridview?在我的例子中,a希望添加一个名为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页面的权限,因此无法使用
模板字段添加它您在雇主中看到“system.web…”的原因是下拉列表是对象,您需要查看其中的数据/值
向该列添加一些定义就可以了
这里有一个以前的工作示例,可以单独查看该列
在代码隐藏中将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行都创建了DropDownList,您可以在GridView的RowDataBound
事件中绑定它 要按照您之前的代码开始这篇文章,这里有一个更新版本,您可以按照它来获得它。(同样,遵循您的语法)
你可以调整到什么程度,因为在这个场景中我可能会说错话
您需要查看其中的数据/值。(我这边的说法是错误的)
这里显示您需要添加控件,控件显示其中的数据/值。(如果这种情况发生在winforms中,这就有点不同了)
希望对您有所帮助。您不能将DropdownList对象绑定到DataRow中,必须从DropdownList中选择一个属性才能显示。例如:drp.Employer.NameI仍然无法解决此问题。您能更具体地说明我应该做什么吗?如果下面的注释没有提供足够的示例,那么我可以得到一个有效的解决方案。@lamnderon-我上面发布的示例是否提供了您想要的解决方案?但我需要重新排列下拉解决方案,因为它显示为您试图创建的上述问题的第一列DropDownList在datatable而不是gridview中动态显示。你能说得更具体些吗?
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);
}