使我的数据对象适合(轻松)与 DataGridView 和/或 DataGrid 一起使用

问题描述 投票:0回答:1
我继承了一个符合IEnumerable的模型对象,但没有继承其他Binding相关的接口。该对象类似于表格,通常填充最终来自 Excel 的数据。读取这些文件的结果是一个 DTable 对象,其中:

    DKeys,行号的整数属性列表 - 不连续或按顺序
  • DRows,一个以这些数字为键、以字典为值的字典
  • DRows 中的 DCell 对象,列名称/值的字典
  • DColumns,包含 DColumn 对象的列表 - 名称、序号位置、格式等。
我对网格控件不熟悉,所以我简单地做了:

Dim BindingSource1 As New BindingSource BindingSource1.DataSource = TestData.Customers DataGridView1.DataSource = BindingSource1 DataGridView1.AutoGenerateColumns = True
...这实际上做了一些事情,它产生了一个单列显示,其中按键的顺序正确。这有点令人惊讶,我认为这根本没有任何作用。我假设它选择了 DKeys,因为这是唯一 IEnumerable 的属性?

MS 文档缺乏解释如何执行此操作的单个文档,并且通常很难理解,因为没有任何内容说“这是您需要做的事情”,它只是一页又一页听起来随机的术语。我相信我需要做的是实现IListSource,特别是GetData和Columns,这是最简单的解决方案吗?

我在这里查看了

许多线程,但其中大多数建议将对象从模型复制到另一个可以正常工作的对象,或者使用 LinQ 来自动执行该复制。我更愿意

那么有人可以给我一本入门书,或者指出一个入门书,它展示了一种“简单的方法”来调整我现有的收藏,使其在网格中“正常工作”吗?

vb.net data-binding datagrid
1个回答
0
投票
当数据绑定对象的属性是另一个对象(来自组合)或其他对象的集合时,DataGridView 将仅显示来自父对象的数据。如果我没记错的话,它将在单元格中显示对象属性类型的值,对于作为对象的父级属性。

我们将当前尝试绑定到 DGV 的对象称为“父”对象。一种可能性是创建一个数据传输对象 (DTO),您可以在其中加载此 DTO 以及您想要显示的 Parent 元素。考虑这个基本示例(凭记忆输入,未经测试):

Public Class MyAddressClass Public Property AddressLine1 As String Public Property AddressLine2 As String Public Property City As String Public Property State As String Public Property ZipCode As String End Class Public Class Customer Public Property ID As Integer Public Property Name As String Public Property Address As MyAddressClass Public Property TelephoneNumbers As List(Of String) Public Property CreateDate As Date Public Property UpdateDate As Date End Class ' Somewhere in the code: Dim customers As New List(Of Customer) = GetTheDataFromSomeDatabase()
现在,假设您想要将 

customers

 中的数据转换为仅正确显示 DGV 中所需的客户数据的视图。

' We only want certain data elements of a customer in the DGV: Public Class CustomerView Public Property Name As String Public Property AddressLine1 As String Public Property AddressLine2 As String Public Property City As String Public Property State As String Public Property ZipCode As String End Class ' Somewhere else in the code, load up a List(of CustomerView) Dim list As New List(Of CustomerView) ' Remember, the "customers" variable was previously loaded from a database. For Each c As Customer In customers Dim cv As New CustomerView With cv .Name = c.Name .AddressLine1 = c.Address.AddressLine1 .AddressLine2 = c.Address.AddressLine2 .City = c.Address.City .State = c.Address.State .ZipCode = c.Address.ZipCode ' We aren't doing anything with c.ID, c.CreateDate, c.UpdateDate ' or c.TelephoneNumbers End With End For ' Now, bind that List(Of CustomerView) to the DataGridView DataGridView1.DataSource = list
这本质上是“展平”您的对象层次结构,仅显示您想要在 DGV 中显示的该层次结构的元素。

© www.soinside.com 2019 - 2024. All rights reserved.