c# - 即使 DataGridView 绑定(bind)到列表,也不会显示任何记录

标签 c# .net winforms data-binding mvp

我已将 List 绑定(bind)到 Presenter 中的 DataGridView,但是当我运行该程序时,仅显示网格列标题,但没有行。

View中有一个封装了DGV的公共(public)属性...

    public BindingSource Employees
    {
        set { dgvEmployees.DataSource = value; }
    }

Prsenter的构造函数中...

  bindingList = new BindingList<IEmployee>(_ModelList); // Presenter has a instance of `List <IEmployee>_ModelList` through the constructor injection
  var source = new BindingSource(bindingList, null);
  _View.Employees = source;

在事件处理程序方法中,我有数据访问代码...

  _ModelList = _DataService.FilterEmployees(_View.EmployeeName); // DataService returns a List<IEmployee>

我的代码中缺少任何内容。在调试中,我注意到 _ModelList 正在填充数据库中的一些项目,但它们都没有显示在网格上?这种方法有什么问题吗?

编辑1:如果我在处理程序方法中这样做,它就可以工作。但我知道这不是正确的做法。

   BindingSource bindingSource = new BindingSource();   
   bindingSource.DataSource = _DataService.FilterEmployees(_View.EmployeeName);
   _View.Employees = bindingSource ;

EDIT2:我找到了另一种更好的方法来做到这一点。

在 Presenters 构造函数中...

    bindingList = new BindingList<IEmployee>();
    _View.Employees = bindingList;

然后在处理程序中...

    var employees = _DataService.FilterEmployees(_View.EmployeeName);
    foreach (IEmployee emp in employees)
    {
        bindingList.Add(emp);
    }

最后将 View 的属性更改为...

    public BindingList<IEmployee> Employees
    {
        set { dgvEmployees.DataSource = value; }
    }

现在一切正常。

有人能告诉我我的第一种方法有什么问题吗?

最佳答案

以下两行将解决您的问题:

        _View.Employees = null;
        _View.Employees = source;

如果将相同的引用绑定(bind)到 DataGridView,它将不会刷新。首先分配空值。对我来说,这看起来像是 DataGridView 控件本身的一个错误(如果我错了,请有人纠正我)。

**Update 1:**

您也可以使用 BindingSource(推荐)或任何集合进行绑定(bind)。在您的新方法中,您将重新创建导致 DataGridView 再次刷新的列表引用。如果您通过将其 DataSource 分配为 null 来删除引用并重新分配另一个引用(如我之前提到的),也可以刷新 DataGridView。

在您的新方法中,您每次都会重新创建列表实例来分配值,并且您将无法利用 BindingSource 中的一些良好的 DataBinding 功能,例如MoveNext、MovePrevious、AddNew 等

关于c# - 即使 DataGridView 绑定(bind)到列表,也不会显示任何记录,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24537391/

相关文章:

c# - 如何将位图转换为图像

c# - 按 T​​ab 键不会选择下一个控件

c# - 如何在winform中制作默认的照片查看器或文本编辑器等

c# - 在特定文档中启用功能区控件 C# vsto 2010

c# - 应用程序运行时替换exe文件

datagridview 的单个单元格中的 C# 多色文本

c# - 64 位 Windows 服务器中的 Sybase 驱动程序错误

c# - 使用 wsdl.exe 从 c# 客户端到 Tomcat 的 HTTPS 连接

c# - 确认服务凭证已更改

c# - 从 Azure 表存储检索超过 100 万条记录