我有一个嵌套的通用列表。我想将其与vb.net中的datagridview绑定。当我绑定列表时,嵌套列仅填充其标题

时间:2018-10-18 07:05:05

标签: .net vb.net list generics datagridview

我有一类物品

 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
----------

当我从数据库中获取列表(项)类中的数据时 它返回这些列。

  1. itemID
  2. itemName
  3. itemCategory

    3(a)itemCategoryID 3(b)itemCategoryName

当我将此列表与Datagridview绑定时,这仅显示三列,第三列填充为列名“ ItemCategory”。我需要在datagridview中显示itemCategoryID和itemCategoryName。

1 个答案:

答案 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