Call the following function in page_load event:
void fill_Tree()
{
//Database db = DatabaseFactory.CreateDatabase("ConStr");
//string sqlCommandName = "Select * from ParentTable";
//DbCommand dbCmd = db.GetSqlStringCommand(sqlCommandName);
//SqlDataReader Sdr = dbCmd.ExecuteReader();
/ SqlCon = new SqlConnection("Data Source=DATABASENAME;Initial Catalog=GKTraining;Persist Security Info=True;User ID=USERID;Password=gK@t#a!n!^T)");
SqlCon.Open();
/*
* Query the database
*/
SqlCommand SqlCmd = new SqlCommand("Select * from a_tbl_parent", 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 a_tbl_child 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";
child.NavigateUrl = Module_Sdr.GetValue(Module_Sdr.GetOrdinal("ChildName")).ToString()+".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();
}
Data binding to TreeView in C#.NET
ReplyDelete