Populating TreeView Control from XML file

Description:

The blog post demonstrates how to populate TreeView Control using XML file in C#.NET. 

The TreeView control has a Nodes collection with root TreeNode objects. Each TreeNode in turn has its own Nodes collection that holds more than one child TreeNode. 

<TreeNode object>.Nodes.Add (TreeNode node) method adds a new TreeNode element with a specified text to the end of the current TreeNode collection. 

Procedure:

Step 1: Variables Declaration

DataSet set = new DataSet();  //To store Tables from XML Document

 

TreeNode parent;              //store Main Table Names

TreeNode child;               //store Contents of Main Table

Listing 1

Step 2: XML file contents tables as shown in below format.

<Customer>

      <Customer CustID="202" Name="Pratik Ghanwat" Contact="8657413501"/>

      <Customer CustID="203" Name="Sohan Dal"      Contact="9746292005"/>

      <Customer CustID="204" Name="Sujit Dalvi"    Contact="8855572178"/>

      <Customer CustID="205" Name="Sushant Shinde" Contact="9835621704"/>

            <Customer CustID="206" Name="Amey Kulkarni"  Contact="9845671203"/>

      </Customer>

Listing 2

Step 3: Now retrieve the values from XML File and add it to the Nodes Collection of TreeView Control.

//Read Contents of XML Document

set.ReadXml(@"..\..\XMLData.xml"); 

for (int i = 0; i < set.Tables.Count; i++) 

{    

      //Get the Name of Main Table

      parent = treeView1.Nodes.Add(set.Tables[i].TableName);

 

      //Get Contents of Main Table

      for (int j = 1; j < set.Tables[i].Rows.Count; j++) 

                    child = parent.Nodes.Add(set.Tables[i].Rows[j][2].ToString());

      }

Listing 3

Intended Result:

New Picture (3).png 


Figure 1  

Summary:

In this writing, we learned how to populate content from XML file to TreeView Control in C#.
X

Build smarter apps with Machine Learning, Bots, Cognitive Services - Start free.

Start Learning Now