TreeView Control Populating with SqlDataSource at runtime.

In Brief:

The article demonstrates how to populate TreeView Control using SqlDataSource at runtime in C#.NET. We can achieve intended result by simply executing SqlCommand Object either by ExecuteReader or ExecuteNonQuery method.

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.

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

Procedure:

Step 1: Declaration of Connection, Command, and DataReader object

SqlConnection Conn = new SqlConnection(“Data Source=.\SQLExpress;

Initial Catalog=NorthWind; Integrated Security=True”);

SqlDataReader rdr;

SqlCommand cmd;

Listing 1

Step 2: Now, whatever the code required to written for populating the SqlDataSource to the TreeView Control you can place it either into the click, load etc. event handlers.

Step 3: We need to create two TreeNode Objects as follows…

TreeNode parent = treeView1.Nodes.Add(“Suppliers”);

TreeNode child;

Listing 2

Step 4: Now pass the SqlQuery as an argument of SqlCommand Object and stored the values into SqlDataReader Object.

cmd = new SqlCommand(“SqlQuery”, Conn);

Conn.Open();

rdr = cmd.ExecuteReader();

Listing 3

Step 5: Now retrieve the values from SqlDataReader and adds it to the Child Nodes of Nodes Collection of TreeView Control.

while (rdr.Read())

{

child = parent.Nodes.Add(“Supplier ID: “ + rdr.GetValue(0).ToString());

child.Nodes.Add(“Name: “ + rdr.GetValue(1).ToString());

.

.

.

}

Listing 4

Intended Result:

Figure 1



Regards,
Mayur Dighe
http://ImmortalDotNet.blogspot.com
http://MayurDighe.wordpress.com