C#DataGridView与Grid.Rows.Add方法的数据绑定错误 [英] C# DataGridView data-bound error with Grid.Rows.Add method

查看:108
本文介绍了C#DataGridView与Grid.Rows.Add方法的数据绑定错误的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在表单上有一个DataGridView。我从数据库中选择一些数据并将其加载到datatable,之后我将这个datatable引用到grid的datasureurce如下。

  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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆