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.Tables.Add(table);
ds.Tables.Add(table1);
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)
{
trv.Nodes.Clear();
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";
trv.Nodes.Add(masterNode);
foreach (DataRow childRow in masterRow.GetChildRows("Children"))
{
TreeNode childNode = new  TreeNode((String)childRow[1], Convert.ToString(childRow[1]));
childNode.ImageUrl = @"Images\Subject.png";
masterNode.ChildNodes.Add(childNode);
count++;
}
}
trv.ExpandAll();
}

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

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s