HOW TO: Populate a TreeView Control from a Dataset in Visual Basic .NET (320755)



The information in this article applies to:

  • Microsoft ADO.NET (included with the .NET Framework 1.1)
  • Microsoft ADO.NET (included with the .NET Framework) 1.0

This article was previously published under Q320755

SUMMARY

This step-by-step article describes how to display data from a hierarchical dataset by using the TreeView control in Microsoft Visual Basic .NET. To do this, you establish a parent, child, and grandchild relationship, and then fill the TreeView control appropriately. The TreeView control has a Nodes collection with root TreeNode objects. Each TreeNode object has its own Nodes collection that holds more than one child TreeNode object. You can then use the TreeView control to work down from the parent or root node to the corresponding child nodes and display the appropriate data.

This example creates a hierarchical dataset, loops through each table, and adds nodes to the TreeView control for each child table in the dataset.

back to the top

Requirements

The following list outlines the recommended hardware, software, network infrastructure, and service packs that are required:
  • Microsoft Visual Studio .NET installed on a compatible Microsoft Windows operating system
  • A SQL server with the sample Northwind database installed
This article assumes that you are familiar with the following topics:
  • Visual Basic .NET
  • ADO.NET data access
back to the top

Create the Project and Add Code

  1. Start Visual Studio .NET, and then create a new Visual Basic Windows Application project.
  2. Add a reference to System.Data.SQLClient by adding the following line to the top of your Form1.vb file:
    Imports System.Data.SqlClient
    					
  3. Drag a TreeView control (Treeview1) from the toolbox to your form (Form1).
  4. Open the form's code window, and then paste the following code into the Form1_Load event:
    Note You must replace USER ID <user name> and PASSWORD <strong password> with the correct values. Make sure that the USER ID has the appropriate permissions to perform these operations on the database.
            Dim DSNWind As DataSet
            Dim CNnwind As New SqlClient.SqlConnection("DATA SOURCE=servername;USER ID=<username>;PASSWORD=<strong password>;INITIAL CATALOG=northwind;") '<==== CHANGE HERE 
            Dim DACustomers As New SqlClient.SqlDataAdapter("SELECT CustomerID, CompanyName, ContactName, Country FROM customers WHERE country = 'Germany'", CNnwind)
            Dim DAOrders As New SqlClient.SqlDataAdapter("SELECT CustomerID, OrderID, OrderDate, ShippedDate, ShipVia, Freight FROM orders where customerid in (select customerid from customers where country = 'Germany')", CNnwind)
            Dim DAOrderDetails As New SqlClient.SqlDataAdapter("Select * from [Order Details] where OrderID in (SELECT OrderID FROM orders where customerid in (select customerid from customers where country = 'Germany'))", CNnwind)
    
            DSNWind = New DataSet()
            CNnwind.Open()
            DACustomers.Fill(DSNWind, "dtCustomers")
            DAOrders.Fill(DSNWind, "dtOrders")
            DAOrderDetails.Fill(DSNWind, "dtOrderDetails")
            'Close the connection to the data store; free up the resources
            CNnwind.Close()
    
            'Create a data relation object to facilitate the relationship between the Customers and Orders data tables.
            DSNWind.Relations.Add("CustToOrd", DSNWind.Tables("dtCustomers").Columns("CustomerID"), DSNWind.Tables("dtOrders").Columns("CustomerID"))
            DSNWind.Relations.Add("OrdToDet", DSNWind.Tables("dtOrders").Columns("OrderID"), DSNWind.Tables("dtOrderdetails").Columns("OrderID"))
            '''''''''''''''''''''''
            TreeView1.Nodes.Clear()
            Dim i, n As Integer
            Dim parentrow As DataRow
            Dim ParentTable As DataTable
            ParentTable = DSNWind.Tables("dtCustomers")
     
            For Each parentrow In ParentTable.Rows
                Dim parentnode As TreeNode
                parentnode = New TreeNode(parentrow.Item(0))
                TreeView1.Nodes.Add(parentnode)
                ''''populate child'''''
                '''''''''''''''''''''''
                Dim childrow As DataRow
                Dim childnode As TreeNode
                childnode = New TreeNode()
                For Each childrow In parentrow.GetChildRows("CustToOrd")
                    childnode = parentnode.Nodes.Add(childrow(0) & " " & childrow(1) & " " & childrow(2))
                    childnode.Tag = childrow("OrderID")
                    ''''populate child2''''
                    ''''''''''''''''''''''''''
                    Dim childrow2 As DataRow
                    Dim childnode2 As TreeNode
                    childnode2 = New TreeNode()
                    For Each childrow2 In childrow.GetChildRows("OrdToDet")
                        childnode2 = childnode.Nodes.Add(childrow2(0))
    
                    Next childrow2
                    ''''''''''''''''''''''''
    
                Next childrow
                '''''''''''''''
            Next parentrow
    					
  5. Modify the connection string point to point to the Northwind database on your SQL server.
  6. Press CTRL+F5 to run the program.
back to the top

REFERENCES

For additional information about populating a TreeView control in Visual Basic .NET, click the article number below to view the article in the Microsoft Knowledge Base:

308063 HOW TO: Populate a TreeView Control with XML Data in Visual Basic .NET

back to the top

Modification Type:MajorLast Reviewed:10/31/2003
Keywords:kbHOWTOmaster KB320755 kbAudDeveloper