Link to home
Start Free TrialLog in
Avatar of transstates
transstatesFlag for United States of America

asked on

Load Treeview using Dataset

Good Morning All,

What am I doing wrong?  What I have is a dataset that has three fields (parent, pn, sn) and I want these to display in a treeview as follows:

        Parent
            pn
                 sn
                 sn
             pn
                  sn
                  sn

and so on.  What I get when I run my code is the parent multiple times.  I want 1 parent with ? of children with ? of sub children.  Heres a piece of code I'm using:
 
       tv.nodes.clear
       tv.BeginUpdate()
        Dim dt As DataTable = dsData.Tables("table1")
        For Each dr As DataRow In dt.Rows
           
            Dim tnRoot As TreeNode = New TreeNode(dr.Item("parent").ToString)
            tnRoot.Nodes.Add(dr.Item("pn").ToString)
            tnRoot.Nodes.Add(dr.Item("sn").ToString)
            tv.Nodes.Add(tnRoot)

        Next
        tv.EndUpdate()

This displays:

Parent
   -->pn
   -->sn(this is the subchild)

Parent (same as above)
   -->pn (same as above)
   -->sn (different)

Hope this makes sense?!?!

Thanks in advance...

jim
Avatar of Nasir Razzaq
Nasir Razzaq
Flag of United Kingdom of Great Britain and Northern Ireland image

I think you need to change this

        For Each dr As DataRow In dt.Rows
           
            Dim tnRoot As TreeNode = New TreeNode(dr.Item("parent").ToString)
            tnRoot.Nodes.Add(dr.Item("pn").ToString)
            tnRoot.Nodes.Add(dr.Item("sn").ToString)
            tv.Nodes.Add(tnRoot)

        Next

to

        For Each dr As DataRow In dt.Rows
           
            Dim tnRoot As TreeNode
            If tv.Nodes.ContainsKey(dr.Item("parent")) Then
               tnRoot  = tv.Nodes(dr.Item("parent"))
            Else
               tnRoot  = New TreeNode(dr.Item("parent").ToString)
            End If
            tnRoot.Nodes.Add(dr.Item("pn").ToString)
            tnRoot.Nodes.Add(dr.Item("sn").ToString)
            tv.Nodes.Add(tnRoot)

        Next
Avatar of transstates

ASKER

Thanks for the help CC:

Ok, in my dataset I have multiple parent number each with mulitiple pn but different sn.  So right now it displays like this:

1170AB (parent)
     1133 (pn)
      AB23 (sn)

1170AB (parent)
     1133 (pn)
      DEF12 (sn)

and so on.....

I'm trying for this:

1170AB (parent)
     1133 (pn)
           AB23 (sn)
           DEF12 (sn)

Hope this helps.. !!!  :)

jim
Did you try my code?
Yes I did.  My last comment was the results.
ASKER CERTIFIED SOLUTION
Avatar of Nasir Razzaq
Nasir Razzaq
Flag of United Kingdom of Great Britain and Northern Ireland image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial