Populating TreeView Control from XML file

Populating TreeView Control from XML file post thumbnail image


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.
Step 1: Variables Declaration
DataSet set = new DataSet();  //To store Tables from XML Document
TreeNodeparent;              //store Main Table Names
TreeNodechild;               //store Contents of Main Table
Listing 1
Step 2: XML file contents tables as shown in below format.
      <Customer CustID=202 Name=Pratik GhanwatContact=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/>
            <CustomerCustID=206 Name=Amey Kulkarni  Contact=9845671203/>
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
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:

Figure 1: Output
In this writing, we learned how to populate content from XML file to TreeView Control in C#.
Mayur Dighe

Leave a Reply

Your email address will not be published. Required fields are marked *