You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

DataGridView数据绑定后无法编程添加行的问题求助

问题解决:DataGridView数据绑定状态下新增行的正确方式

错误原因

当DataGridView处于数据绑定状态时,不能直接调用DataGridView.Rows.Add()添加行,所有数据操作必须通过绑定的数据源(比如DataTable、BindingList<T>)来完成,这是数据绑定控件的核心规则。


具体解决方案

1. 确保加载TXT数据时使用可绑定数据源

不要直接往DataGridView里塞行,而是把TXT数据加载到DataTable(或自定义实体类的BindingList<T>),再将数据源绑定到DataGridView。

示例:Form1加载TXT到DataTable

private void Form1_Load(object sender, EventArgs e)
{
    // 创建对应7列的DataTable
    DataTable dataTable = new DataTable();
    for (int i = 0; i < 7; i++)
    {
        dataTable.Columns.Add($"列{i+1}");
    }

    // 读取TXT文件(假设是逗号分隔,根据实际分隔符调整)
    string[] lines = File.ReadAllLines("你的文件路径.txt");
    foreach (string line in lines)
    {
        string[] values = line.Split(',');
        if (values.Length == 7)
        {
            dataTable.Rows.Add(values);
        }
    }

    // 绑定数据源到DataGridView
    dataGridView1.DataSource = dataTable;
}

2. 在Form2中通过数据源新增行

点击ADD按钮时,直接操作Form1绑定的数据源,而非DataGridView本身:

示例:Form2的ADD按钮事件

private void btnAdd_Click(object sender, EventArgs e)
{
    // 获取Form1实例(如果是Form1打开的Form2,也可以在打开时直接传递引用)
    Form1 mainForm = Application.OpenForms.OfType<Form1>().FirstOrDefault();
    if (mainForm == null) return;

    // 获取绑定的DataTable
    DataTable dataTable = mainForm.dataGridView1.DataSource as DataTable;
    if (dataTable == null) return;

    // 创建新行并填充文本框值
    DataRow newRow = dataTable.NewRow();
    newRow[0] = textBox1.Text;
    newRow[1] = textBox2.Text;
    // 依次填充剩余5列...
    newRow[6] = textBox7.Text;

    // 将新行添加到数据源,DataGridView会自动刷新
    dataTable.Rows.Add(newRow);

    this.Close(); // 可选:添加完成后关闭Form2
}

额外说明:使用自定义实体类的情况

如果用自定义实体类存储数据,需要用BindingList<T>包装列表,确保数据源变更时DataGridView自动刷新:

// Form1中绑定数据源
BindingList<YourEntity> dataList = new BindingList<YourEntity>(你的实体列表);
dataGridView1.DataSource = dataList;

// Form2中新增行
dataList.Add(new YourEntity { 
    属性1 = textBox1.Text,
    属性2 = textBox2.Text,
    // 其他属性...
});

内容的提问来源于stack exchange,提问作者nom.23

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.24 17:07:03