【问题标题】:I have a nested Generic List. I want to bind it with datagridview in vb.net. when i bind the list, the nested column only fill with its heading我有一个嵌套的通用列表。我想将它与 vb.net 中的 datagridview 绑定。当我绑定列表时,嵌套列仅填充其标题
【发布时间】:2018-10-18 07:05:04
【问题描述】:

我有一类物品

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

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

  1. 项目ID
  2. 项目名称
  3. 项目类别

    3(a) itemCategoryID 3(b) 项目类别名称

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

【问题讨论】:

  • 这不会靠魔法发生。网格只会为实际属性或属性描述符创建列。由于您没有这些属性,因此您需要属性描述符,这意味着自定义类型描述符。这是您需要研究并尝试自己实施的主题。如果您在这样做时遇到实际问题,我们可以尝试专门提供帮助。不过,这个主题过于宽泛,无法给出具体答案。
  • 顺便说一句,我刚刚测试了是否可以自己创建列并将DataPropertyName 设置为“ItemCategory.ItemCategoryID”之类的值,但它不起作用。这些列中的单元格是空的,输入值对绑定的项目没有影响。

标签: .net vb.net list generics datagridview


【解决方案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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2019-08-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-09-27
    • 1970-01-01
    • 2022-01-21
    相关资源
    最近更新 更多