4

我有一个网格,当数据加载到网格中时;我只需选择一行并按编辑按钮。编辑时,打开新的子表单,并将行单元格的值传递给子表单上的控件。但是,当我更改子表单上的某些值并将它们保存以在网格中替换时,我遇到了错误:当控件为数据绑定时,无法以编程方式将行添加到 DataGridView 的行集合中。这个错误的原因是什么以及如何克服这个错误。

4

3 回答 3

4

原因是“当控件绑定数据时,无法以编程方式将行添加到 DataGridView 的行集合中”。它像结晶水一样清澈

解决方案?不要行添加到 DataGridView 的行集合中,将它们添加到基础数据源集合(您要设置到 DataGridView 的 DataSource 属性中的集合)

于 2012-07-12T05:16:18.547 回答
1

在. DataSource_ 不要直接添加/编辑到您的网格。DataGridView

如果您DataSource is DataSet和您想添加新行

DataSet dsTempDataTable = (DataSet)MainApplication.dgvBooksDetails.DataSource;
DataTable dt = dsTempDataTable.Tables[0]; // use table index/name to get the exact table
DataRow dr = dt.NewRow();
//  code to fill record
dt.Rows.Add(dr);

编辑

DataSet dsTempDataTable = (DataSet)MainApplication.dgvBooksDetails.DataSource;
DataTable dt = dsTempDataTable.Tables[0]; // use table index/name to get the exact table
dt.Rows[0]["columnName"] = "some value";
// your row edit  code
dt.AcceptChanges();
于 2012-07-12T05:25:51.967 回答
0

我有同样的问题,我找到了解决方案。

//create datatable and columns
DataTable dtable = new DataTable();
dtable.Columns.Add(new DataColumn("Column 1"));
dtable.Columns.Add(new DataColumn("Column 2"));

//simple way create object for rowvalues here i have given only 2 add as per your requirement
object[] RowValues = { "", "" };

//assign values into row object
RowValues[0] = "your value 1";
RowValues[1] = "your value 2";

//create new data row
DataRow dRow;
dRow = dtable.Rows.Add(RowValues);
dtable.AcceptChanges();

//now bind datatable to gridview... 
gridview.datasource=dtable;
gridview.databind();

资料来源: http: //www.codeproject.com/Questions/615379/Adding-rows-to-datagridview-with-existing-columns

于 2015-08-10T14:11:40.163 回答