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

BindingList已更新但DataGridView未刷新,求基于给定代码的解决方案

解决BindingList更新后DataGridView未同步的问题

嘿,我看你遇到了BindingList更新后DataGridView没同步的问题,结合你贴的代码,我帮你梳理几个最常见的排查方向和解决办法:

1. 先检查InventoryTransaction类是否实现了INotifyPropertyChanged

BindingList默认只会在集合里新增、删除、排序元素时自动通知DataGridView更新,但如果是修改了集合中某个对象的属性值,就需要这个对象本身实现INotifyPropertyChanged接口,否则DataGridView根本不知道属性变了。

给你个示例写法,照着改你的InventoryTransaction类就行:

public class InventoryTransaction : INotifyPropertyChanged
{
    // 举个例子,假设你有个Quantity属性
    private int _quantity;
    public int Quantity
    {
        get => _quantity;
        set
        {
            if (_quantity != value)
            {
                _quantity = value;
                OnPropertyChanged(nameof(Quantity));
            }
        }
    }

    // 实现INotifyPropertyChanged的必要事件和方法
    public event PropertyChangedEventHandler PropertyChanged;

    protected virtual void OnPropertyChanged(string propertyName)
    {
        PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
    }
}

2. 确认更新BindingList的操作在UI线程

WinForms的控件只能在UI线程操作,如果你的InventoryTransactions是在后台线程(比如定时器、异步方法)里更新的,DataGridView肯定不会同步。这种情况要切换回UI线程再操作:

// 比如你在定时器或者异步方法里更新,用Invoke切回UI线程
this.Invoke((Action)(() =>
{
    // 这里执行BindingList的新增、修改、删除操作
    InventoryTransactions.Add(new InventoryTransaction());
}));

3. 检查BindingSource的配置有没有问题

你已经把BindingSource的DataSource设为InventoryTransactions了,但要注意:如果中途你重新给barCodeForm_InventoryTransactionBindingSource.DataSource赋值,或者不小心改了它的引用,会导致绑定失效。

另外,如果是批量更新BindingList,建议先暂时关闭事件通知,更新完再打开,还能提升性能:

InventoryTransactions.RaiseListChangedEvents = false;
// 这里批量添加/修改元素
InventoryTransactions.RaiseListChangedEvents = true;
// 手动触发一次列表变更通知,确保DataGridView收到更新
InventoryTransactions.ResetBindings();

4. 核对DataGridView的列绑定是否正确

确认DataGridView的每一列的DataPropertyName都和InventoryTransaction类的属性名完全一致(大小写敏感!),比如列要绑定Quantity属性,就不能写成quantity或者其他名字。

应急方案:手动触发更新

如果以上都排查过还是不行,可以在更新完BindingList后手动调用这两个方法强制同步:

// 让BindingSource重置绑定
barCodeForm_InventoryTransactionBindingSource.ResetBindings(false);
// 或者直接刷新DataGridView
dataGridView1.Refresh();

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.26 09:13:13