简体   繁体   中英

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

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.

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

请直接将行添加到数据表中,因为它绑定到数据表,所以它对gridview起作用。

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM