2012-07-12 45 views
3

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

+0

那么你可以在你设定的DataGridView的'DataSource'物业的行/记录添加到您的数据源 – V4Vendetta 2012-07-12 04:52:28

+0

? – Talha 2012-07-12 04:56:11

+0

好吧,我有一个DataSet作为Grid的DataSource。我如何在DataSet中添加行或者我需要将行添加到表中,然后将该表添加到数据集中? – 2012-07-12 05:32:30

回答

3

原因是“控件数据绑定时行不能以编程方式添加到DataGridView的行集合”。它与结晶水一样清澈

解决方案?难道行添加到DataGridView的行集合,将它们添加到底层数据源集合(在您设置到DataGridView的DataSource属性的集合)

1

添加或编辑你的行中的DataGridViewDataSource不要直接添加/编辑到您的网格。

如果您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(); 
+1

dt.Row [0]:这里0表示行的索引?而且我怎么可以处理更多的行中的一列?我的意思是,如果我在一行中有7列,可以将值设置为单元格? – 2012-07-12 05:37:45

+0

@ Itz.Irshad非常简单,你可以使用像这样的列名.. dt.Rows [0] [“column1”] =“value1”; dt.Rows [0] [“column2”] =“value2”; dt.Rows [0] [“column3”] =“value3”;等等 – Talha 2012-07-12 05:57:06

+0

是的,我做到了。但是,因为我有一个'DataSet'作为'DataSource'到'Grid' ....所以得到这个错误:*无法将类型为'System.Data.DataSet'的对象转换为键入'System.Data.DataTable' 。*在第一行有代码:'DataTable dtTempDataTable =(DataTable)MainApplication.dgvBooksDetails.DataSource;' – 2012-07-12 06:00:41

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

相关问题