Click here to Skip to main content
15,913,944 members
Please Sign up or sign in to vote.
3.40/5 (2 votes)
See more:
Hi friends!
I have a DB in Access, it looks like this

Field1    Field2
100000    Active
110000    Current Active
111000    Availavilities
111100    Money Box
111101    MoneyBox1
111102    MoneyBox2
111103    MoneyBox3

With this Data i want to Populate a Treeview
It should look like this

Active
|--Current Active
   |--Availavilities
      |--Money Box
         |--MoneyBox1
         |--MoneyBox2
         |--MoneyBox3


I'm working with this code (i'm missing all the logic to write the nodes as i want)

Thank you so much!!!!!!!!!!


VB
Private Sub FormTreeViewPC_Load(sender As Object, e As EventArgs) Handles MyBase.Load

    '//LOADS ALL THE DATA
    tv.Nodes.Clear()

    CMD.Connection = conn
    CMD.CommandType = CommandType.Text

    SQL = "SELECT FIELD1, FIELD2 FROM PLANCUENTAS" & cuitClient & ""

    CMD.CommandText = SQL
    Try
        dr = CMD.ExecuteReader

        While dr.Read

        End While
        dr.Close()
    Catch ex As Exception
        MsgBox(ex.ToString)
    End Try
End Sub
Posted
Updated 5-Feb-15 10:16am
v2

1 solution

I'll assume the ID (Field1) values are integers rather than strings.
If you sort by Field1 the task can be done in one pass, but you don't say, so I'll assume you do.
I'd use a Dictionary<int,TreeNode> to hold the nodes.

0) Instantiate a Dictionary
1) For each record in the DataReader
1.1) Instantiate a TreeNode to hold the data
1.2) Add the TreeNode to the Dictionary
1.3) Search for a parent (X=10)
1.3.1) Divide the ID by X, then multiply by X
1.3.2) If the new value is zero, there is no parent -- add the node to the Tree's Nodes collection
1.3.3) Else if the new value exists in the Dictionary, we have found the parent, add the node to the parent's Nodes collection
1.3.4) Else multiply X by 10 and repeat from 1.3.1


(Edit: Reworked the parent ID search algorithm. I may need to try it to be sure it's correct.)
 
Share this answer
 
v4

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900