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
How to add New Row in datagridview which is bound to the datasource
提问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 DataGridView
is data bound to some data source then you cannot add new rows/columns. You will have to create a new data set (DataTable
or whatever) with the required columns and then re-bind the DataGridView
to that.
不,如果DataGridView
数据绑定到某个数据源,则不能添加新的行/列。您将不得不DataTable
使用所需的列创建一个新的数据集(或其他),然后将其重新绑定DataGridView
到该列。
I hope this helps.
我希望这有帮助。
回答by Kurubaran
It seems that you are using the DataSource
property 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 BindingSource
instead and you will preserve NewRow
绑定到 aBindingSource
而您将保留 NewRow