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

Isenção de Responsabilidade para Conteúdo da KB Desativado

Este artigo foi escrito sobre produtos para os quais a Microsoft já não fornece suporte. Por conseguinte, este artigo é oferecido "tal como está" e não será mais atualizado.


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.


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

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()
    DACustomers.Fill(DSNWind, "dtCustomers")
    DAOrders.Fill(DSNWind, "dtOrders")
    DAOrderDetails.Fill(DSNWind, "dtOrderDetails")
    'Close the connection to the data store; free up the resources

    '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"))
    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))
    ''''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.


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

ID do Artigo: 320755 - Última Revisão: 30 de out de 2003 - Revisão: 1