سؤال

I'm trying to achive something really simple here. I just want a treeview that groups by the root item so that all the children show up under the common root.

In the example below i have 4 students and 3 coaches. However two of the students belong to the same coach. I want those two students two show up under the same root rather than creating another as its currently doing. Can anyone help with this?

Current Code:

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

Current Output:

enter image description here

هل كانت مفيدة؟

المحلول

Try using a Dictionary to keep a reference of the parent nodes you are using:

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()
مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top