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