我隐藏了asp:gridviewrows基于网格中的复选框,如果它们被隐藏,我不想将它们插入到数据表中。我正在尝试以下语法,但我收到了
的调试错误附加信息:名为' column0'的列。已经属于这个DataTable。
这行代码抛出错误datatablefirst.Columns.Add ....
如何更改语法以删除此问题?
foreach (GridViewRow row in gridviewmain.Rows)
{
CheckBox chk = (CheckBox)row.Cells[0].FindControl("checkboxforcode");
if (chk.Checked == true)
{
for (int i = 0; i < gridviewmain.Columns.Count; i++)
{
datatablefirst.Columns.Add("column" + i.ToString());
}
DataRow dr = datatablefirst.NewRow();
for (int j = 0; j < gridviewmain.Columns.Count; j++)
{
dr["column" + j.ToString()] = row.Cells[j].Text;
}
datatablefirst.Rows.Add(dr);
}
}
答案 0 :(得分:1)
如果列不存在,您只想添加列。那不是每行都做的。
bool columnsAdded = false;
foreach (GridViewRow row in gridviewmain.Rows)
{
CheckBox chk = (CheckBox)row.Cells[0].FindControl("checkboxforcode");
if (chk.Checked == true)
{
if (!columnsAdded )
{
for (int i = 0; i < gridviewmain.Columns.Count; i++)
{
datatablefirst.Columns.Add("column" + i.ToString());
}
columnsAdded = true;
}
DataRow dr = datatablefirst.NewRow();
for (int j = 0; j < gridviewmain.Columns.Count; j++)
{
dr["column" + j.ToString()] = row.Cells[j].Text;
}
datatablefirst.Rows.Add(dr);
}
}