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

C#实现ListBox数据追加至DataGridView不覆盖原有数据的方案

问题解决方案

核心问题分析

  1. 数据覆盖问题:每次调用Data_ID_Load时都会新建DataTable并直接赋值给DataGridView的DataSource,导致原有数据被完全替换。
  2. ListBox修改影响DataGridView:原有逻辑依赖ListBox实时生成DataTable,修改ListBox后重新导出会覆盖原有数据,造成“DataGridView随ListBox变更”的错觉。

具体修改方案

1. 定义全局DataTable变量

将DataTable改为窗体类的成员变量,用于保留历史数据:

private DataTable _gridDataTable;

2. 初始化DataTable

在窗体构造函数(或Load事件)中初始化DataTable并绑定到DataGridView:

public YourFormClassName() // 替换为你的窗体类名
{
    InitializeComponent();
    // 初始化DataTable并添加列
    _gridDataTable = new DataTable();
    _gridDataTable.Columns.Add("Label ID", typeof(string));
    _gridDataTable.Columns.Add("Serial Number", typeof(string));
    _gridDataTable.Columns.Add("Item Name", typeof(string));
    _gridDataTable.Columns.Add("Item ID", typeof(string));
    // 绑定数据源
    gridview.DataSource = _gridDataTable;
}

3. 修改Data_ID_Load方法

改为向已有的DataTable追加数据(可选添加重复检查避免重复行):

public void Data_ID_Load()
{
    // 检查ComboBox和TextBox有效性
    if (cmbitemname.SelectedItem == null)
    {
        MetroMessageBox.Show(this, "请选择Item Name", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
        return;
    }
    string cmbItemName = cmbitemname.SelectedItem.ToString();
    string cmbItemID = txtitemsku.Text?.Trim() ?? string.Empty;
    if (string.IsNullOrEmpty(cmbItemID))
    {
        MetroMessageBox.Show(this, "Item ID不能为空", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
        return;
    }

    // 遍历ListBox,追加数据到DataTable
    for (int i = 0; i < lstlabelid.Items.Count; i++)
    {
        // 可选:检查是否已存在相同Label ID的行,避免重复
        bool isDuplicate = false;
        foreach (DataRow row in _gridDataTable.Rows)
        {
            if (row["Label ID"].ToString() == lstlabelid.Items[i].ToString())
            {
                isDuplicate = true;
                break;
            }
        }
        if (!isDuplicate)
        {
            _gridDataTable.Rows.Add(
                lstlabelid.Items[i].ToString(),
                lstserialno.Items[i].ToString(),
                cmbItemName,
                cmbItemID
            );
        }
    }
    // 无需重新绑定数据源,DataTable更新后DataGridView会自动刷新
}

4. 保持原按钮事件逻辑不变

btnexport_Click方法无需修改,仍调用Data_ID_Load即可。

效果说明

  • 再次导出数据时,原有数据会保留,新数据将追加到DataGridView中。
  • 修改ListBox内容不会影响已导出到DataGridView的历史数据,只有再次点击导出时才会添加新的ListBox数据。

内容的提问来源于stack exchange,提问作者Aberam Wijayakumar

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.27 02:47:08