当控件为数据绑定时,无法以编程方式将行添加到 datagridview 的行集合中 [英] Rows cannot be programmatically added to the datagridview's row collection when the control is data-bound

查看:28
本文介绍了当控件为数据绑定时,无法以编程方式将行添加到 datagridview 的行集合中的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

首先,我在此处 但解决方案 dataGridView1.Rows.Add() 在我的情况下不起作用.

First of all, I looked up this related question in here but the solution dataGridView1.Rows.Add() doesn't work in my case.

在我的 Datagridview 中,我有 3 个文本框用于数据输入和 2 个组合框供用户选择值(绑定到数据库中).我的一个 TextBoxes 设置为只读,以便用户只能在数据网格之外填充它(使用普通的 TexBox 和一个按钮).

In my Datagridview, I have 3 TextBoxes for data input and 2 ComboBoxes for the user to choose the values (which are bound into the database). One of my TextBoxes is set to read only so that the users can only populate it outside the datagrid (with a normal TexBox and a Button).

当用户用数据填充DataGridView时,底部总是有一个空行;所以我禁用了它并使用此代码来防止用户在数据网格中添加新行...

When the users fill a DataGridView with data, there is always an empty row at the bottom; so I disable this and I used this code to prevent the users from adding a new row inside the datagrid...

dataGridView1.AllowUserToAddRows = false

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

I only want to add a new row when the users click the button I mentioned above (which throws an error).

我得到的错误信息是:

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

"Rows cannot be programmatically added to the datagridview's row collection when the control is data-bound"

带红色箭头的是ComboBox,带绿色箭头的是只读TextBox

the one with a red arrow is a ComboBox, and the one with green arrow is a read only TextBox

推荐答案

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

It appears as though 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.

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

For example if your data source is a DataTable, using the DataTable that is assigned to the DataSource property (untested):

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);
}

这篇关于当控件为数据绑定时,无法以编程方式将行添加到 datagridview 的行集合中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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