Dim BindingSource1 As New BindingSource
BindingSource1.DataSource = TestData.Customers
DataGridView1.DataSource = BindingSource1
DataGridView1.AutoGenerateColumns = True
...这实际上做了一些事情,它产生了一个单列显示,其中按键的顺序正确。这有点令人惊讶,我认为这根本没有任何作用。我假设它选择了 DKeys,因为这是唯一 IEnumerable 的属性?
MS 文档缺乏解释如何执行此操作的单个文档,并且通常很难理解,因为没有任何内容说“这是您需要做的事情”,它只是一页又一页听起来随机的术语。我相信我需要做的是实现IListSource,特别是GetData和Columns,这是最简单的解决方案吗?
我在这里查看了许多线程,但其中大多数建议将对象从模型复制到另一个可以正常工作的对象,或者使用 LinQ 来自动执行该复制。我更愿意
那么有人可以给我一本入门书,或者指出一个入门书,它展示了一种“简单的方法”来调整我现有的收藏,使其在网格中“正常工作”吗?
我们将当前尝试绑定到 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 中显示的该层次结构的元素。