C# DataGridView data-bound error with Grid.Rows.Add method

旧时模样 提交于 2020-01-06 19:39:12

问题


i have a DataGridView on the Form. I select some data from database and load them to datatable and after that i make reference this datatable to grid's datasorurce as below.

string sql = "";
sql = "SELECT id,name,surname,code FROM t_persons";
DataTable dt = new DataTable();
...
adapter.Fill(dt);
grid.DataSource = dt;

and after that i want to add new row to this grid with grid.Rows.Add() method. But every time it gives an error Rows cannot be programmatically added to the DataGridView's rows collection when the control is data-bound.
So whatis the problem and how can i solve it.


回答1:


You should add row to the DataTable, not to the DataGridView. That is what the exception is saying. Try:

DataRow newRow = dt.NewRow();
dt.Rows.Add(newRow);



回答2:


Please you can add row directly to datatable and it's effect on gridview because it's bind to datatable.



来源:https://stackoverflow.com/questions/12088042/c-sharp-datagridview-data-bound-error-with-grid-rows-add-method

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