C#DataGridView与Grid.Rows.Add方法的数据绑定错误 [英] C# DataGridView data-bound error with Grid.Rows.Add method
问题描述
string sql =;
sql =SELECT id,name,surname,code FROM t_persons;
DataTable dt = new DataTable();
...
adapter.Fill(dt);
grid.DataSource = dt;
之后,我想使用 grid.Rows.Add向该网格添加新行()方法。但是每当它发出错误当控件是数据绑定的时候,行不能以编程方式添加到DataGridView的行集合。
那么问题是什么,我该如何解决它。
您应该向DataTable添加行,而不是DataGridView。这就是异常说的。尝试:
DataRow newRow = dt.NewRow();
dt.Rows.Add(newRow);
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);
这篇关于C#DataGridView与Grid.Rows.Add方法的数据绑定错误的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!