TreeView – from datatables

I will demonstrate the basics for creating a treeview from2 different tables:

Let’s take 2 datatable for example:

DataTable table = new DataTable();
table.Columns.Add("QueueID", typeof(string));
table.Columns.Add("Queue", typeof(string));
table.Rows.Add("1", "Queue 1");
table.Rows.Add("2", "Queue 2");
table.Rows.Add("3", "Queue 3");
table.Rows.Add("4", "Queue 4");
table.Rows.Add("5", "Queue 5");
table.Rows.Add("6", "Queue 6");
table.Rows.Add("7", "Queue 7");
table.Rows.Add("8", "Queue 8");
DataTable table1 = new DataTable();
table1.Columns.Add("QueueID", typeof(string));
table1.Columns.Add("Subject", typeof(string));
table1.Rows.Add("1", "Subject 1");
table1.Rows.Add("1", "Subject 2");
table1.Rows.Add("2", "Subject 1");
table1.Rows.Add("2", "Subject 2");
table1.Rows.Add("2", "Subject 3");
table1.Rows.Add("2", "Subject 4");
table1.Rows.Add("3", "Subject 1");
table1.Rows.Add("3", "Subject 2");

Now,we need to create a relation between those two datatables :

DataSet ds = new  DataSet();
ds.Relations.Add("Children", table.Columns[0], table1.Columns[0]);//define parent child relation in dataset

We will now represent the following relation in a Treeview with Queue as the Parent Node and the Subjects as the child node.

if (ds.Tables[0].Rows.Count > 0)
Int32 count = 0;
foreach (DataRow masterRow in ds.Tables[0].Rows)
TreeNode masterNode = new  TreeNode((String)masterRow[1], Convert.ToString(masterRow[0]));
masterNode.ImageUrl =  @"Images\QueueuImage.png";
foreach (DataRow childRow in masterRow.GetChildRows("Children"))
TreeNode childNode = new  TreeNode((String)childRow[1], Convert.ToString(childRow[1]));
childNode.ImageUrl = @"Images\Subject.png";

Below is the snapshot of the treeview that will be created by the above given code snippets.