[英]Rows cannot be added programmatically in the DataGridView when the control data-bound
In my DatagridView already have data, then i want to add new row when click add button in windows form i got "Rows cannot add programmatically to the datagridview row collection when in the controls data-bound.在我的 DatagridView 中已经有数据,然后我想在 Windows 窗体中单击添加按钮时添加新行我得到“当在控件数据绑定中时,行无法以编程方式添加到 datagridview 行集合。
Then i google it i got some answer like you can use DataTable to add a new row, below code i used然后我谷歌它我得到了一些答案,比如你可以使用 DataTable 添加一个新行,下面是我使用的代码
Then, i tried to run,然后,我试着跑,
in my datagrid shows rows added but with blank values for all rows like a empty row在我的数据网格中显示添加的行,但所有行的值都为空值,如空行
kindly suggest me where i'm wrong i'm new at windows application datagridview with c#请告诉我我错在哪里我是 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;
}
I couldn't get why you do all of these things.我不明白你为什么要做所有这些事情。 You said you have data in your dataGridView, Mean you have already set headers of the dataGridView and you just want to add new row while clicking on the button.您说您的 dataGridView 中有数据,这意味着您已经设置了 dataGridView 的标题,并且您只想在单击按钮时添加新行。 If my perception is right then you just do the below thing on button click event.如果我的看法是正确的,那么您只需对按钮单击事件执行以下操作即可。
dataGridView1.Rows.Add("Column1", "Column2",..);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.