Deborah's Developer MindScape






         Tips and Techniques for Web and .NET developers.

November 9, 2009

Populating a TreeView Control from a List

Filed under: C#,VB.NET,WinForms @ 11:25 pm

This post details first how to build a list containing the data to display in a WinForms TreeView control. Then it demonstrates how to use recursion to populate the TreeView control from the list.

[For information on populating a TreeView control from XML, see this link.]

First, create a class that will store the data for the TreeView.

In C#:

public class TreeViewItem
{
    public int ID { get; set; }
    public int ParentID { get; set; }
    public string Text { get; set; }
}

In VB:

Public Class TreeViewItem
    Public Id As Integer
    Public ParentId As Integer
    Public Text As String
End Class

The C# code uses auto-implemented properties to short-cut the code. The VB code is just me being lazy tonight. It is using Public fields instead of Public Properties as it should. (In VS 2010, VB will have auto—implemented properties as well.)

The class defines an Id associated with the item and a ParentId defining the Id of the parent item (that is the item under which this item will appear in the TreeView). It also has a Text property that contains the text of the TreeView node.

In the WinForm containing the TreeView control, add the code to build the list as shown below.

In C#:

List<TreeViewItem> treeViewList = new List<TreeViewItem>();

treeViewList.Add(new TreeViewItem() { 
          ParentID = 0, ID = 1, Text = "Parent node" });
treeViewList.Add(new TreeViewItem() { 
          ParentID = 1, ID = 2, Text = "First child node" });
treeViewList.Add(new TreeViewItem() { 
         ParentID = 1, ID = 3, Text = "Second child node" });
treeViewList.Add(new TreeViewItem() { 
         ParentID = 3, ID = 4, Text = "Child of second child node" });
treeViewList.Add(new TreeViewItem() { 
         ParentID = 3, ID = 5, Text = "Child of second child node" });

PopulateTreeView(0, null);

In VB:

Private treeViewList As New List(Of TreeViewItem)

treeViewList.Add(New TreeViewItem() With { _
        .ParentId = 0, .Id = 1, .Text = "Parent node"})
treeViewList.Add(New TreeViewItem() With { _
        .ParentId = 1, .Id = 2, .Text = "First child node"})
treeViewList.Add(New TreeViewItem() With { _
        .ParentId = 1, .Id = 3, .Text = "Second child node"})
treeViewList.Add(New TreeViewItem() With { _
        .ParentId = 3, .Id = 4, .Text = "Child of second child node"})
treeViewList.Add(New TreeViewItem() With { _
        .ParentId = 3, .Id = 5, .Text = "Child of second child node"})

PopulateTreeView(0, Nothing)

This code defines a generic List that contains the set of TreeViewItem instances. The Add method of the list sets the data into the list. It then calls the PopulateTreeView method (shown below).

The PopulateTreeView method uses recursion to populate the TreeView from the list.

In C#:

private void PopulateTreeView(int parentId, TreeNode parentNode)
{
    var filteredItems = treeViewList.Where(item => 
                                item.ParentID == parentId);

    TreeNode childNode;
    foreach (var i in filteredItems.ToList())
    {
        if (parentNode == null)
            childNode = treeView1.Nodes.Add(i.Text);
        else
            childNode = parentNode.Nodes.Add(i.Text);

        PopulateTreeView(i.ID, childNode);
    }
}

In VB:

Private Sub PopulateTreeView(ByVal parentId As Integer, _
                             ByVal parentNode As TreeNode)
    Dim filteredItems = treeViewList.Where(Function(item) _
                                     item.ParentId = parentId)

    Dim childNode As TreeNode
    For Each i In filteredItems.ToList()
        If parentNode Is Nothing Then
            childNode = TreeView1.Nodes.Add(i.Text)
        Else
            childNode = parentNode.Nodes.Add(i.Text)
        End If
        PopulateTreeView(i.Id, childNode)
    Next
End Sub

The PopulateTreeView method has two parameters: parentId and parentNode. The parentId is the Id value associated with the parent node. The code will find all items in the list with the defined parent Id. The parentNode is the TreeView node under  which the items are added.

The filteredItems variable contains the results of a lambda expression finding all of the items in the list with the passed in parentId.

The code then loops through those items and adds the nodes to the parent node.

It then calls itself, making the method recursive. The method call passes in the node’s Id and the node itself. This will cause the method to load all of its child nodes.

When you run the code, the TreeView should appear as follows:

image

Enjoy!

12 Comments

  1.   dellmerca — February 20, 2012 @ 12:13 pm    Reply

    asp.net treeview from vb.net and c#

    http://asp.net-informations.com/webcontrols/asp-net-treeview.htm

    dell.

  2.   ESM — April 26, 2013 @ 4:54 pm    Reply

    Thank you very much for taking the time to write this useful tutorial!

RSS feed for comments on this post. TrackBack URI

Leave a comment

*

© 2014 Deborah's Developer MindScape   Provided by WPMU DEV -The WordPress Experts   Hosted by Microsoft MVPs