Rows cannot be programmatically added to the DataGridView's rows collection when the control is data-bound

雨燕双飞 提交于 2020-01-20 06:50:09

问题


I have a grid and when data is loaded in grid; I simply select a row and press edit button. On edit, new sub form is opened and values of row's cells are passed to controls on sub form. But, when I change some values on sub form and save them to be replaces in grid the error comes to me: Rows cannot be programmatically added to the DataGridView's rows collection when the control is data-bound. What is cause of this error and how to overcome this.


回答1:


The cause is that "Rows cannot be programmatically added to the DataGridView's rows collection when the control is data-bound". It is as clear as crystalline water

The solution? Do not add rows to the DataGridView's rows collection, add them to the underlying datasource collection (the collection you are setting in to the DataSource property of the DataGridView)




回答2:


Add or Edit your row in DataSource of your DataGridView. Do not directly add/edit to your grid.

If your DataSource is DataSet and you want to add new row

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);

To Edit

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();



回答3:


I had the same problem and I found solution.

//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();

Source: http://www.codeproject.com/Questions/615379/Adding-rows-to-datagridview-with-existing-columns



来源:https://stackoverflow.com/questions/11445121/rows-cannot-be-programmatically-added-to-the-datagridviews-rows-collection-when

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!