我有一类物品
Public Class Item
Public Property ItemID() As Integer
Public Property ItemName() As String
Public Property itemCategory() As ItemCategory
End class
---------
Another Class of ItemCategory
Public Class ItemCategory
Public Property ItemCategoryID() As Integer
Public Property ItemCategoryName() As String
End Class
----------
当我从数据库中获取列表(项)类中的数据时 它返回这些列。
itemCategory
3(a)itemCategoryID 3(b)itemCategoryName
当我将此列表与Datagridview绑定时,这仅显示三列,第三列填充为列名“ ItemCategory”。我需要在datagridview中显示itemCategoryID和itemCategoryName。
答案 0 :(得分:1)
正如@jmcilhinney指出的那样,没有任何魔法,datagridview
需要知道如何显示ItemCategory
。
一个选项是创建“ viewmodel”类,该类将为DataGridView
提供属性。
从数据库填充的类:
(您不需要在每个属性中都有重复的类名,并且无需类名前缀即可轻松读取属性)
Public Class Item
Public Property ID As Integer
Public Property Name As String
Public Property Category As ItemCategory
End class
Public Class ItemCategory
Public Property ID As Integer
Public Property Name As String
End Class
然后创建viewmodel类,它将表示DatagridView所需的所有属性
Public Class ItemViewModel
Private ReadOnly _item As Item
Public Property Id As String
Get
Return _item.ID
End Get
End Property
' Add setter if you want edit values through DataGridView
Public Property Name As String
Get
Return _item.Name
End Get
End Property
Public Property CategoryId As String
Get
Return _item.Category.ID
End Get
End Property
Public Property CategoryName As String
Get
Return _item.Category.Name
End Get
End Property
Public Sub New(item As Item)
_item = item
End Sub
End class
然后您可以将viewmodel绑定到DataGridView
Dim items As List(Of Item) = LoadFromDatabase()
Dim viewmodels = items.Select(Function(item) new ItemViewModel(item)).ToList()
myDataGridView.DataSource = viewmodels