TreeView Group by root

时间:2014-03-24 13:43:05

标签: vb.net treeview ms-access-2007

我试图在这里做一些非常简单的事情。我只想要一个按根项目分组的树视图,以便所有子项都显示在公共根目录下。

在下面的例子中,我有4名学生和3名教练。然而,其中两名学生属于同一位教练。我希望这两个学生两个出现在同一个根目录下,而不是像现在这样创建另一个。任何人都可以帮忙吗?

当前代码:

    '//LOADS ALL THE DATA 
    TreeView2.Nodes.Clear()
    Dim Connection As OleDbConnection = New OleDbConnection("Provider=Microsoft.ACE.OLEDB.12.0;Data Source=./AcademyDatabase.accdb;Persist Security Info=False;")
    Dim Command As OleDbCommand = New OleDbCommand("Select DISTINCT Coach, FullName from Student ORDER BY Coach")
    Command.Connection = Connection
    Command.Connection.Open()


    '//RUN COMMAND 
    Dim DataReader As OleDbDataReader = Command.ExecuteReader()

   '//RUN COMMAND 
    Dim rows As Integer = 0


    While DataReader.Read()
        Dim columns As Integer


        TreeView2.Nodes.Add(DataReader(0).ToString())
        For columns = 1 To DataReader.FieldCount - 1
            TreeView2.Nodes(rows).Nodes.Add(DataReader.Item(columns).ToString())
        Next


        rows += 1
    End While

当前输出:

enter image description here

1 个答案:

答案 0 :(得分:1)

尝试使用Dictionary来保留您正在使用的父节点的引用:

Dim coaches As New Dictionary(of String, TreeNode)
While DataReader.Read()
  Dim coachNode As TreeNode = Nothing
  If coaches.ContainsKey(DataReader(0).ToString) Then
    coachNode = coaches(DataReader(0).ToString)
  Else
    coachNode = New TreeNode(DataReader(0).ToString)
    coaches.Add(DataReader(0).ToString, coachNode)
    TreeView2.Nodes.Add(coachNode)
  End If
  coachNode.Nodes.Add(DataReader(1).ToString)
End While
TreeView2.ExpandAll()