当控件是数据绑定时,无法以编程方式将行添加到datagridview的行集合中

首先,我在这里查找了这个相关的问题,但解决方案dataGridView1.Rows.Add()在我的情况下不起作用。

在我的Datagridview中,我有3个TextBox用于数据输入,2个ComboBox用于用户选择值(绑定到数据库中)。 我的一个TextBox被设置为只读,以便用户只能在数据网格外部填充它(使用普通的TexBox和一个Button)。

当用户用数据填充DataGridView时,底部总是有一个空行; 所以我禁用了这个,我用这个代码阻止用户在datagrid中添加一个新行…

 dataGridView1.AllowUserToAddRows = false 

我只想在用户单击上面提到的按钮时添加一个新行(这会引发错误)。

我得到的错误信息是:

“当控件受数据绑定时,无法以编程方式将行添加到datagridview的行集合中”

样本图像 带有红色箭头的那个是ComboBox,带绿色箭头的那个是只读的TextBox

看起来好像您正在使用DataGridView的DataSource属性。 当此属性用于绑定到数据时,您无法将行直接显式添加到DataGridView。 您必须直接向数据源添加行。

例如,如果您的数据源是DataTable,则使用分配给DataSource属性的DataTable(未测试):

 private void AddARow(DataTable table) { // Use the NewRow method to create a DataRow with // the table's schema. DataRow newRow = table.NewRow(); // Add the row to the rows collection. table.Rows.Add(newRow); } 

您可以获取DataGridViewDataSource并将其转换为DataTable

然后添加一个新的DataRow并设置字段的值。

将新行添加到DataTable并接受更改。

在C#中它会是这样的:

 DataTable dataTable = (DataTable)dataGridView.DataSource; DataRow drToAdd = dataTable.NewRow(); drToAdd["Field1"] = "Value1"; drToAdd["Field2"] = "Value2"; dataTable.Rows.Add(drToAdd); dataTable.AcceptChanges(); 

添加新行后,必须在行计数的边界设置行索引。 你必须做这些步骤。

  1. 首先,在DataGridView中添加行:

     dataGridView1.Rows.Add(); 
  2. 其次,将新行索引设置为count – 1:

     int RowIndex = dataGridView1.RowCount - 1; 
  3. 最后,在其中设置控件值:

     DataGridViewRow R = dataGridView1.Rows[RowIndex]; R.Cells["YourName"].Value = tbName.Text; 

如果你的datagrid的源是datattable,你必须在该表中添加行。给数据表中新添加的行赋予新值,最后用更新的数据表重新绑定datagrid。

  DataRow row = dt.NewRow(); row["columnname"] = tbName.Text.toString(); dt.Rows.Add(row); dt.AcceptChanges(); dataGridView1.DataSource = dt; dataGridView1.DataBind(); 

检查是否已正确设置新行的索引。 也许这就是你得到这个错误的原因。

Bound Datagridview存在一个问题,当您想以编程方式添加数据时,它会阻止它直接添加它。 所以添加数据的间接和最佳方式就是这样..并且记住永远不要以编程方式直接向datagridview添加数据,因为它总是会产生问题,而是将数据添加到数据源中:-)

 code for VB.NET Dim r As DataRow ( C# : Datarow r=new Datarow() below codes apply to C# also) r = dataset.Tables(0).NewRow r.Item("field1") = "2" r.Item("field2") = "somevalue" dataset.Tables(0).Rows.Add(r) dataset.Tables(0).acceptchanges() the update will goes as you do ever 

我找到的最佳解决方案:

 //create datatable and columns DataTable dtable = new DataTable(); dtable.Columns.Add(new DataColumn("Column 1")); dtable.Columns.Add(new DataColumn("Column 2")); //simple way create object for rowvalues here i have given only 2 add as per your requirement object[] RowValues = { "", "" }; //assign values into row object RowValues[0] = "your value 1"; RowValues[1] = "your value 2"; //create new data row DataRow dRow; dRow = dtable.Rows.Add(RowValues); dtable.AcceptChanges(); //now bind datatable to gridview... gridview.datasource=dtable; gridview.databind(); 

资料来源: http : //www.codeproject.com/Questions/615379/Adding-rows-to-datagridview-with-existing-columns