[英]Rows cannot be programmatically added to the DataGridView's rows collection when the control is data-bound
[英]Rows cannot be added programmatically in the DataGridView when the control data-bound
在我的 DatagridView 中已经有数据,然后我想在 Windows 窗体中单击添加按钮时添加新行我得到“当在控件数据绑定中时,行无法以编程方式添加到 datagridview 行集合。
然后我谷歌它我得到了一些答案,比如你可以使用 DataTable 添加一个新行,下面是我使用的代码
然后,我试着跑,
在我的数据网格中显示添加的行,但所有行的值都为空值,如空行
请告诉我我错在哪里我是 Windows 应用程序 datagridview 的新手,使用 c#
DataTable dataTable=new DataTable();
foreach (DataGridViewColumn col in dataGridView.Columns)
{
dataTable.Column.add(col.Name);
}
foreach (dataGridViewRow row in dataGridView.Rows)
{
DataRow drow=dataTable.NewRow();
foreach (DataGridViewCell cell in row.cells)
{
drow[cell.ColumnIndes]=cell.value;
dataTable.Rows.add(drow);
}
}
//then,
//i assigned dataTable values to dataGridView
dataGridView.DataSource=dataTable;
}
我不明白你为什么要做所有这些事情。 您说您的 dataGridView 中有数据,这意味着您已经设置了 dataGridView 的标题,并且您只想在单击按钮时添加新行。 如果我的看法是正确的,那么您只需对按钮单击事件执行以下操作即可。
dataGridView1.Rows.Add("Column1", "Column2",..);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.