我正在尝试将dropdownlist添加到gridview中的列。我有这样的事情:
DataTable dt = new DataTable();
DataColumn dc = new DataColumn();
if (dt.Columns.Count == 0)
{
dt.Columns.Add("Names", typeof(string));
dt.Columns.Add("Selection", typeof(string));
}
DropDownList ddlSelection= new DropDownList();
ddlSelection.Items.Add(new ListItem("one"));
ddlSelection.Items.Add(new ListItem("two"));
DataRow NewRow = dt.NewRow();
NewRow[0] = lblname.Text;
NewRow[1] = ddlSelection.Items;
dt.Rows.Add(NewRow);
我收到了一个类型的错误。谁可以帮助我?
谢谢!
答案 0 :(得分:0)
我不认为您可以向DataTable添加控件,尝试处理gridview的DataBound操作并使用foreach(GridView1.rows中的GridViewRow)循环迭代,将控件添加到gridview中的任何一个单元格
//edit:
protected void Page_Load(object sender, EventArgs e)
{
DataTable dt = new DataTable();
DataColumn dc = new DataColumn();
if (dt.Columns.Count == 0)
{
dt.Columns.Add("Selection", typeof(string));
dt.Columns.Add("Names", typeof(string));
}
DropDownList ddlSelection = new DropDownList();
ddlSelection.Items.Add(new ListItem("one"));
ddlSelection.Items.Add(new ListItem("two"));
for(int i= 0; i < 10; i++)
{
DataRow NewRow = dt.NewRow();
NewRow[1] = "dropdownlist"+i;
dt.Rows.Add(NewRow);
}
GridView1.DataSource = dt;
GridView1.DataBind();
}
protected void GridView1_DataBound(object sender, EventArgs e)
{
foreach (GridViewRow r in GridView1.Rows)
{
DropDownList ddlSelection = new DropDownList();
ddlSelection.Items.Add(new ListItem("one"));
ddlSelection.Items.Add(new ListItem("two"));
r.Cells[0].Controls.Add(ddlSelection);
}
}
答案 1 :(得分:0)
一种简单的方法是,创建用户控件,并将其作为模板字段加载。 但是每次加载页面时,此模板字段都会清除,因此您需要它来创建每次页面加载。
foreach (DataRow dr in dt.Rows)
{
int index = dt.Rows.IndexOf(dr);
if(index =1)
{
TemplateField tF = new TemplateField();
tF.HeaderText = dr["COLUMN_NAME"].ToString();
tF.ItemTemplate = LoadTemplate("/xxxxxx.ascx");
GridView1.Columns.Add(tF);
}
}