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

编程入门 行业动态 更新时间:2024-10-28 04:24:50
本文介绍了当控件为数据绑定时,无法以编程方式将行添加到 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屋!

更多推荐

[db:关键词]

本文发布于:2023-03-29 10:52:53,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/753637.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:控件   方式   数据   datagridview

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!