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

C# WinForms中BindingSource绑定DataGridView启动时未填充数据的问题

C# WinForms中BindingSource绑定DataGridView启动时未填充数据的问题

嘿,我来帮你排查这个问题!你用MVVM+EF Core做WinForms应用,启动时DataGridView没加载数据,这种情况我之前也遇到过,咱们一步步拆解可能的原因和解决办法:

1. 检查BindingSource的DataMember参数(最可能的核心问题)

你在创建BindingSource的时候写了:

MotherSpools = new BindingSource(ms, "MspoolId");

这里第二个参数"MspoolId"是DataMember,它的作用是指定要绑定的子集合名称,但你现在绑定的是BindingList<MotherspoolGridRow>这个集合本身,不需要指定DataMember(因为你要显示集合里每个对象的属性)。如果指定了"MspoolId",BindingSource会尝试去每个MotherspoolGridRow对象里找名为MspoolId的子集合,而MspoolId是个long类型的单个值,自然找不到数据,导致Grid为空。

解决办法:把DataMember设为null或者空字符串:

MotherSpools = new BindingSource(ms, null);

2. 确认ViewModel属性变化是否通知到了DataGridView

你的Form里是直接赋值DataSource:

MotherSpoolGrid.DataSource = vm.MotherSpools;

虽然你的ViewModel构造函数里同步调用了LoadMotherSpools,但直接赋值的方式不会监听PropertyChanged事件,如果后续MotherSpools属性有变化,Grid也不会自动更新。更稳妥的做法是用数据绑定的方式关联:

// 替换原来的直接赋值
MotherSpoolGrid.DataBindings.Add(
    new Binding("DataSource", vm, nameof(vm.MotherSpools), 
    true, DataSourceUpdateMode.OnPropertyChanged)
);

3. 验证EF Core是否真的加载到了数据

在LoadMotherSpools方法里加个断点,检查ms这个BindingList<MotherspoolGridRow>里有没有元素:

  • 如果ms是空的,那说明EF Core没从数据库查到数据,检查你的eFGContext配置、连接字符串,或者确认数据库里有数据。
  • 如果ms有元素,那问题就出在BindingSource或者DataGridView的绑定上。

4. 检查自定义DataGridViewPersistent的影响

你继承了DataGridView来保存列设置,有可能在保存/加载设置的时候影响了列的显示或者数据绑定。可以暂时换成系统自带的DataGridView测试,如果换成普通Grid后能显示数据,那就是自定义Grid的SaveDisplaySettings或者初始化逻辑有问题,比如加载设置时隐藏了所有列,或者重置了DataSource。

5. 确认DataGridView的AutoGenerateColumns属性

确保你的DataGridView的AutoGenerateColumns属性是true(默认是true,但如果手动修改过就需要检查),这样才能根据MotherspoolGridRow的DisplayName属性自动生成列。如果设为false,又没手动添加列,Grid自然是空的。

按照上面的步骤一步步排查,应该能解决问题。我之前碰到过类似的BindingSource DataMember参数设错的情况,改了之后就正常显示了。

内容来源于stack exchange

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.04.07 11:45:34