void fill_Tree()
{ /* * Fill the treeview control Root Nodes From Parent Table * and child nodes from ChildTables */
/* * Create an SQL Connection to connect to you our database */
SqlConnection SqlCon = new SqlConnection("server=D_hameed;uid=sa;pwd=airforce;database=test");
SqlCon.Open();
/* * Query the database */
SqlCommand SqlCmd = new SqlCommand("Select * from ParentTable",SqlCon);
/* *Define and Populate the SQL DataReader */
SqlDataReader Sdr = SqlCmd.ExecuteReader();
/* * Dispose the SQL Command to release resources */
SqlCmd.Dispose ();
/* * Initialize the string ParentNode. * We are going to populate this string array with our ParentTable Records * and then we will use this string array to populate our TreeView1 Control with parent records */
string[,] ParentNode = new string[100, 2];
/* * Initialize an int variable from string array index */
int count = 0;
/* * Now populate the string array using our SQL Datareader Sdr.
* Please Correct Code Formatting if you are pasting this code in your application. */
while (Sdr.Read()) {
ParentNode[count, 0] = Sdr.GetValue(Sdr.GetOrdinal("ParentID")).ToString(); ParentNode[count++, 1] = Sdr.GetValue(Sdr.GetOrdinal("ParentName")).ToString();
}
/* * Close the SQL datareader to release resources */
Sdr.Close();
/* * Now once the array is filled with [Parentid,ParentName] * start a loop to find its child module. * We will use the same [count] variable to loop through ChildTable * to find out the number of child associated with ParentTable. */
for (int loop = 0; loop < count; loop++)
{
/* * First create a TreeView1 node with ParentName and than * add ChildName to that node */
TreeNode root = new TreeNode(); root.Text = ParentNode[loop, 1]; root.Target = "_blank";
/* * Give the url of your page */
root.NavigateUrl = "mypage.aspx";
/* * Now that we have [ParentId] in our array we can find out child modules
* Please Correct Code Formatting if you are pasting this code in your application.
*/
SqlCommand Module_SqlCmd = new SqlCommand("Select * from ChildTable where ParentId =" + ParentNode[loop, 0], SqlCon);
SqlDataReader Module_Sdr = Module_SqlCmd.ExecuteReader();
while (Module_Sdr.Read()) {
// Add children module to the root node
TreeNode child = new TreeNode();
child.Text = Module_Sdr.GetValue(Module_Sdr.GetOrdinal("ChildName")).ToString();
child.Target = "_blank";
child.NavigateUrl = "your_page_Url.aspx";
root.ChildNodes.Add(child);
}
Module_Sdr.Close();
// Add root node to TreeView TreeView1.Nodes.Add(root);
}
/* * By Default, when you populate TreeView Control programmatically, it expends all nodes. */ TreeView1.CollapseAll(); SqlCon.Close();
} |