0

我有这个名为“产品”的数据集,它的结构如下:

ProductID  ProductGroup  ProductName
1          Drinks        Water
2          Other         Fries1
3          Other         Fries2
4          Other         Fries3

我想以这样一种方式填充我的 TreeView,即为每个 ProductGroup(不重复)创建一个节点,并将该行上的 ProductName 添加到创建的节点中。

有什么线索吗?

4

1 回答 1

0
Public Class Form1
    Private _dt As DataTable

    Private Sub Form1_Load(sender As System.Object, e As System.EventArgs) Handles MyBase.Load
        _dt = New DataTable
        _dt.Columns.Add("ProductID", GetType(Integer))
        _dt.Columns.Add("ProductGroup", GetType(String))
        _dt.Columns.Add("ProductName", GetType(String))
        _dt.Rows.Add(1, "Drinks", "Water")
        _dt.Rows.Add(2, "Other", "Fries1")
        _dt.Rows.Add(3, "Other", "Fries2")
        _dt.Rows.Add(4, "Other", "Fries3")

        'Note: Casting can be removed if using a typed datatable

        'Create a root node for each product group, using the product group as the node's key
        Dim ProductGroups = (From rw In _dt Select CType(rw("ProductGroup"), String) Distinct).ToArray

        For Each grp In ProductGroups
            TreeView1.Nodes.Add(grp, grp)
        Next

        'Add each product to the appropriate node
        For Each rw In _dt.Rows
            TreeView1.Nodes(CType(rw("ProductGroup"), String)).Nodes.Add(CType(rw("ProductName"), String))
        Next
    End Sub
End Class
于 2013-11-04T15:08:08.273 回答