DataGridView的复杂结合复杂、DataGridView

2023-09-06 22:44:45 作者:柳叶眉霓裳影

我要绑定列在一个DataGridView从两个不同的类中提取值。我的应用是在WinForms的。

I want to bind columns in a DataGridView to pull values from two different classes. My application is in WinForms.

我有一个这样的数据结构:

I have a data structure like this:

Class A
    Number As Integer
    Items as List(Of Class B)
End Class

Class B
    Number as Integer
    Value as Double
End Class

我需要能够在与所述第一列被A.Number和后续列是在项目列表中的每个项目一个DataGridView显示此。

I need to be able to display this in a DataGridView with the first column being A.Number and subsequent columns being each item in the Items list.

Items
1     1-1.5     2-2.0     3-3.6
2     1-1.0     2-3.9     3-4.2
.
.
.

我已经迄今为止唯一的建议是可行的似乎在短时间内是将其转换为一个DataTable和绑定的,但这似乎非常难看。

The only suggestion I've had so far that seemed workable in a short period of time was to convert this to a datatable and bind that, but this seems very ugly.

感谢您的帮助!

推荐答案

有好几次,我有一个数据网格,我想从几个不同的地方拉列。最简单的方法,我发现是创建一个显示类,这只是一堆getter方法​​来浏览一些对象模型。然后,我绑定到该显示类。

Several times, I've had a data grid that I wanted to pull columns from a couple of different places. The easiest technique I found was to create a display class that is just a bunch of getter methods to navigate some object model. Then I bind to that display class.

在这个例子中,你必须做这样的事情:

In this example, you'd have to do something like this:

Class ADisplay
    private A target
    public ADisplay(A target)
        Me.target = target
    End

    public property Number
        return target.Number
    End

    public property Item0
        return FormatItem(0)
    End

    public property Item1
        return FormatItem(1)
    End
    ...
    private Function FormatItem(i as Integer) As String
        B item = target.Items(i)
        ' Now format that item
        ...

对不起,我的VB.NET是很生疏,但我希望这是十分清楚你的想法。

Sorry, my VB.NET is very rusty, but I hope it's clear enough for you to get the idea.