ABCDE ABCDE - 1 month ago 31
Vb.net Question

How to populate treeview control with data from database vb.net

This is my code:

While dr2.Read()
Dim node = New TreeNode(dr2("chapterno").ToString)
geo.Nodes("toc").Nodes.Add(node)
node.Nodes.Add(dr2("lessonno").ToString)
End While


I have a database with two tables. one for the chapters and one for the lessons of each chapter. I want my
TreeView
to look like Chapter 1 (parent node) has Lesson 1, Lesson 2, etc.. as its child node. but when I run my code, it has too many chapter 1, each has one lesson in it. please help me. big thanks!

Answer

Not tested, but the concept is: You need to remember the last chapter added to your treeview and the node used. If the chapter is still the same then add only the lesson using the chapter node, if the chapter is different add a new chapter node and set the variables used to guard your loop to the last values

Dim node as TreeNode = Nothing
Dim lastChapter as String = String.Empty
While dr2.Read()
    Dim curChapter = dr2("chapterno").ToString
    if curChapter Is Nothing OrElse curChapter <> lastChapter Then
        node = New TreeNode(curChapter)
        lastChapter = curChapter
        geo.Nodes("toc").Nodes.Add(node)
    End If
    node.Nodes.Add(dr2("lessonno").ToString)
End While