Populating Treeview with N- Level Tree Structure Dynamically in VB.Net
From last two weeks I was facing a problem regarding populating a treeview on a vb .net form , with the data from a table which contains N level of child nodes. I searched but i couldnt find exact solution, anyways finally I was able to solve it using recursive function....
Here is the code... The database table has two fields one is AcCode and 2nd is Parent ID...
Private Sub AddTreeNodes(ByRef tv As TreeView)
Dim tda As SqlDataAdapter
Dim tds As DataSet
Dim tdv As DataView
Dim node As TreeNode
Dim pnode As TreeNode
''Clear Tree View
tv.Nodes.Clear()
'Add Top most Node
node = tv.Nodes.Add("0", "Chart of Accounts of " & gCompanyName, 1)
pnode = node
'Check How many Level Exists
Try
tda = New SqlDataAdapter("SELECT * FROM Acc_AccChart Where AcLevel = 1 " & _
" AND CompanyID = " & gDefaultCompany & " ORDER BY AcCode", cn)
tds = New DataSet
tda.Fill(tds, "Acc_AccChart")
tdv = New DataView(tds.Tables(0))
If tdv.Count > 0 Then
For Each tdr As DataRow In tdv.Table.Rows
''Add Head of Accounts
node = pnode.Nodes.Add(tdr.Item(0).ToString(), tdr.Item(0).ToString() & _
" - " & tdr.Item(2).ToString(), IIf(tdr.Item(10).ToString() = "True", 2, 1))
Call AddChildNodes(node, tdr.Item(0).ToString())
Next
End If
Catch ex As SqlException
MessageBox.Show(ex.Message, "Exception", MessageBoxButtons.OK, MessageBoxIcon.Error)
Me.Close()
Finally
tv.Nodes("0").Expand()
End Try
Exit Sub
End Sub
Private Sub AddChildNodes(ByRef node As TreeNode, ByRef nodeID As String)
Dim tda As SqlDataAdapter
Dim tds As DataSet
Dim tdv As DataView
Dim ppnode As TreeNode
ppnode = node
Try
tda = New SqlDataAdapter("SELECT * FROM Acc_AccChart WHERE CompanyID = " & _
gDefaultCompany & " AND AcLinked = '" & nodeID & "' ORDER BY AcCode", cn)
tds = New DataSet
tda.Fill(tds, "Acc_AccChart")
tdv = New DataView(tds.Tables(0))
If tdv.Count > 0 Then
For Each tdr As DataRow In tdv.Table.Rows
node = ppnode.Nodes.Add(tdr.Item(0).ToString(), tdr.Item(0).ToString() & _
" - " & tdr.Item(2).ToString(), IIf(tdr.Item(10).ToString() = "True", 2, 1))
'RECURSIVE CALL
Call AddChildNodes(node, tdr.Item(0).ToString())
Next
Else
Exit Sub
End If
Catch ex As Exception
MessageBox.Show(ex.Message, "Exception", MessageBoxButtons.OK, MessageBoxIcon.Error)
Me.Close()
Finally
tda = Nothing
tds = Nothing
tdv = Nothing
End Try
End Sub
Download project
PLEASE WRITE MY CODE FOR ME
Add new comment
- Add new comment
- 348 views