C# 如何在绑定到数据源的datagridview中添加新行

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/18915116/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-10 13:35:09  来源:igfitidea点击:

How to add New Row in datagridview which is bound to the datasource

c#winformsdatagridview

提问by Amit Kumar

I have a datagridview that is bound to a datasource. I have to add a new row in datagridview when I click Edit button or New button.I tried some code but its giving me error, code is given below

我有一个绑定到数据源的数据网格视图。当我单击“编辑”按钮或“新建”按钮时,我必须在 datagridview 中添加一个新行。我尝试了一些代码,但它给了我错误,代码如下

DataGridView grdview = new DataGridView();
grdview.Rows.Add();
grdview.Rows[grdview.Rows.Count - 1].Cells[0].Selected = true;
grdview.BeginEdit(false);

I also tried typecasting of datasource to datatable but no solution.

我也尝试将数据源类型转换为数据表,但没有解决方案。

回答by MoonKnight

No, if the DataGridViewis data bound to some data source then you cannot add new rows/columns. You will have to create a new data set (DataTableor whatever) with the required columns and then re-bind the DataGridViewto that.

不,如果DataGridView数据绑定到某个数据源,则不能添加新的行/列。您将不得不DataTable使用所需的列创建一个新的数据集(或其他),然后将其重新绑定DataGridView到该列。

I hope this helps.

我希望这有帮助。

回答by Kurubaran

It seems that you are using the DataSourceproperty of the DataGridView. When this property is used to bind to data you cannot explicitly add rows directly to the DataGridView. You must instead add rows directy to your data source.

看来,您正在使用DataSource的财产DataGridView。当此属性用于绑定到数据时,您不能直接将行显式添加到 DataGridView。您必须改为将行直接添加到您的数据源

If you are binding a List

If you are binding a List

//Assume Student list is bound as Dtaasource
List<Student> student = new List<Student>();

//Add a new student object to the list
student .Add(new Student());

//Reset the Datasource
dataGridView1.DataSource = null;
dataGridView1.DataSource = student;

If you are binding DataTable

If you are binding DataTable

DataTable table = new DataTable();

 DataRow newRow = table.NewRow();

// Add the row to the rows collection.
table.Rows.Add(newRow);

回答by Mauro Sampietro

Bind to a BindingSourceinstead and you will preserve NewRow

绑定到 aBindingSource而您将保留 NewRow