簡體   English   中英

當控件是數據綁定的時,不能以編程方式將行添加到DataGridView的rows集合中

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

我有一個網格,並且在網格中加載數據時; 我只需選擇一行,然后按編輯按鈕。 在編輯時,將打開新的子窗體,並將行單元格的值傳遞給子窗體上的控件。 但是,當我更改子窗體上的某些值並將其保存以替換為網格時,出現了錯誤: 當控件綁定數據時,無法以編程方式將行添加到DataGridView的rows集合中 什么是此錯誤的原因以及如何解決此問題。

原因是“控件綁定數據時,無法以編程方式將行添加到DataGridView的行集合中”。 像結晶水一樣清澈

解決辦法 不要行添加到DataGridView的行集合,將它們添加到底層數據源收集(你在到DataGridView的DataSource屬性設置集合)

DataGridView DataSource中添加或編輯行。 不要直接在網格中添加/編輯。

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

我遇到了同樣的問題,並且找到了解決方案。

//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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM