0

我有以下结构

matrix As Dictionary(Of String, Dictionary(Of Class1, Class2))

我想把这个结构的所有元素放在一个 datagridview 中,如下所示:

Column1: String   | Column2: Class1.name     | column3: class2.name

有人知道如何解决这个问题吗?我是 datagridviews 的新手,所以不知道如何开始添加行和列(也许自动生成列??)

4

1 回答 1

1

测试和工作样本:

Public Class Class1
  Public name As String
End Class
Public Class Class2
  Public name As String
End Class

Private Sub Form1_Load(sender As System.Object, e As System.EventArgs) Handles MyBase.Load
  Dim matrix As New Dictionary(Of String, Dictionary(Of Class1, Class2))
  matrix.Add("hello", New Dictionary(Of Class1, Class2))
  matrix("hello").Add(New Class1 With {.name = "123"}, New Class2 With {.name = "321"})

  Dim dt As New DataTable
  With dt.Columns
    .Add("Column1")
    .Add("Column2")
    .Add("Column3")
  End With
  For i = 0 To matrix.Count - 1
    Dim key As String = matrix.Keys(i)
    Dim value As Dictionary(Of Class1, Class2) = matrix.Values(i)
    For j = 0 To value.Count - 1
      Dim class1Name As String = value.Keys(j).name
      Dim class2Name As String = value.Values(j).name
      Dim dr As DataRow = dt.NewRow
      With dr
        .Item("Column1") = key
        .Item("Column2") = class1Name
        .Item("Column3") = class2Name
      End With
      dt.Rows.Add(dr)
    Next
  Next
  dataGridView1.DataSource = dt
End Sub
于 2012-10-31T12:18:17.863 回答