Click here to Skip to main content
15,867,568 members
Articles / Programming Languages / C#
Tip/Trick

Populate TreeView from Simple "list"

Rate me:
Please Sign up or sign in to vote.
4.40/5 (4 votes)
27 Aug 2012CPOL1 min read 58.7K   1.5K   8   5
How to SIMPLY populate TreeView from some sort of "list" variable / object / structure

Introduction

This tip explains a very simple example on how to populate TreeView from some sort of list.

In this example, I used  List<class> as variable, but it can easily be array or something similar.

It is written using Visual C# 2010 Express, but it should be easily adapted to C/C++, VB...

Background

It's becoming ever harder and frustrating to find simplified examples on how to do a simple task: like populate TreeView.

As a hardware engineer, often I have to waste hours to find out how to add two and two. Examples often unnecessary use eighteen layers of abstraction with data coming over SXw satellite link form XttAS database over ISPR4 link ... (you got the idea Smile | <img src= ) just to show you how to change text in EditBox!

Screenshot

Image 2

Using the Code

  1. Copy-paste the complete source file to a new project
  2. Add controls to Form:
    • TreeView tvData
    • Button btnPopulate
    • ListBox lbData containing Items:
      • 0 Movies
      • 1 Comedy
      • 1 SF
      • 2 5th Element
      • 3 Bruce Willis
      • 3 Mila Jovovic
      • 2 Matrix
      • 0 Music
      • 1 Alternative
      • 1 R&R
      • 2 Coldplay
      • 1 Clasic
      • 0 Pictures
      • 1 Trips
      • 2 Europe
      • 3 Stuttgart
      • 4 Mercedes-Benz museum
      • 2 Africa
Here is the complete code that you can just copy-paste to a new project:

C#
using System;
using System.Collections.Generic;
using System.Linq;
using System.Windows.Forms;

namespace TreeViewExample
{
   public partial class Form1 : Form
   {
      public class kData {   // instead of class you can use struct, but with some difficulties
         public int index;
         public int level;
         public string NodeText;
         public string OtherData;
         //public stData()  { } // here you can initialize variables
      };
      List<kData> L; // instead of list you can use array, but I prefer Lists

      public Form1() {
         InitializeComponent();
      }

      private void btnPopulate_Click(object sender, EventArgs e) {
         // take data from ListBox and store it to List
         string line;
         L = new List<kData>();
         for (int i = 0; i < lbData.Items.Count; i++)  {
            line = lbData.Items[i].ToString();
            L.Add(new kData());
            L[i].index = i;
            L[i].level = Convert.ToInt32(line.Substring(0,1));
            L[i].NodeText = line.Substring(2);
            L[i].OtherData = "some other data you might need";
         }

         populateBaseNodes();
      }

      public void populateBaseNodes()
      {
         int i;
         tvData.Nodes.Clear();
         tvData.BeginUpdate();

         for (i = 0; i < L.Count(); i++) {
            if (L[i].level == 0) {
               tvData.Nodes.Add(L[i].NodeText, L[i].NodeText);
               tvData.Nodes[tvData.Nodes.Count - 1].Tag = L[i];
            }
         }

         for (i = 0; i < tvData.Nodes.Count; i++)
            populateChilds(tvData.Nodes[i]);

         tvData.EndUpdate();
         tvData.Refresh();
      }

      public void populateChilds(TreeNode parentNode)  
      {
         kData parentRed = (kData)parentNode.Tag;

         for (int i = parentRed.index + 1; i < L.Count; i++) {
            if (L[i].level == (parentRed.level + 1)) {
               parentNode.Nodes.Add(L[i].NodeText, L[i].NodeText);
               parentNode.Nodes[parentNode.Nodes.Count - 1].Tag = L[i];
               populateChilds(parentNode.Nodes[parentNode.Nodes.Count - 1]);
            }
            if (L[i].level <= parentRed.level) break;
         }
      }
   }
} 

Final Note

The code should be self-explanatory.

If it isn't, then I have failed in my attempt and feel free to give it bad marks. Smile | <img src=

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)


Written By
Yugoslavia Yugoslavia
This member has not yet provided a Biography. Assume it's interesting and varied, and probably something to do with programming.

Comments and Discussions

 
QuestionHow to clear all TreeView nodes? Pin
Transmay24-Oct-12 3:15
Transmay24-Oct-12 3:15 
Generalclearly Pin
Transmay24-Oct-12 3:08
Transmay24-Oct-12 3:08 
GeneralMy vote of 2 Pin
fredatcodeproject27-Aug-12 7:15
professionalfredatcodeproject27-Aug-12 7:15 
GeneralRe: My vote of 2 Pin
textorijum27-Aug-12 16:02
textorijum27-Aug-12 16:02 
GeneralRe: My vote of 2 Pin
fredatcodeproject28-Aug-12 4:34
professionalfredatcodeproject28-Aug-12 4:34 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.