Explanation:To add multi-nodes with sub-nodes in the TreeView is kind of different approach. I came to idea to add new Article as we saw some guys asking this question in ASP .NET Forum.
We will use Iterator technique to add the Nodes and subnodes. For that we need a Collection. There are many ways to create a Collection. Array of Strings, Rows Collection of DataTable or MembersCollection in new Profiling system in ASP .NET 2.0.
Here we will get a simple example of a DataTable Rows Collection. I think the code is self explained. If still you see some lines of code to be explained please ask.
Now, See how we are adding nodes to the Treeview.
private void TasksNodes_Load(object sender, EventArgs e)
{
this.treeView1.Nodes.Add("Tasks");
try
{
DatabaseOperations dbopration = new DatabaseOperations();
//This class contains the logic of the Data operations
DataTable myTable = dbopration.LoadTasksTable();
//Loads Tasks from the Database
foreach (DataRow row in myTable.Rows)
{
if (!string.IsNullOrEmpty(row[1].ToString()))
{
TreeNode node = new TreeNode(@"Task: " + row[1].ToString());
this.treeView1.Nodes[0].Nodes.Add(node);
TreeNode node2 = new TreeNode(@"FullTaskName: " + row[2].ToString());
node.Nodes.Add(node2);
}
}
this.treeView1.Sorted = true;
this.treeView1.Nodes[0].Expand();
Cursor.Position = new Point(Location.X + 30, Location.Y + 30);
//Move the Mouse curser to the first Node
}
catch (OleDbException exp)
{
MessageBox.Show("Error: {0}" + exp.Errors[0].Message);
}
}
Now see how we are selecting the treeview node.
private void treeView1_DoubleClick(object sender, EventArgs e)
{
if (treeView1.SelectedNode.IsSelected)
{
this.SelectedTreePath = selectAllPath(this.treeView1.SelectedNode);
//SelectedTreePath is a string type Variable defined in the Class
this.DialogResult = DialogResult.OK;
//To close the Popup Form. otherwise remove this line
}
}
private string selectAllPath(TreeNode ThisSelectedNode)
{
string selcetedAbove = ThisSelectedNode.FullPath;
string selectedBelow = string.Empty;
foreach (TreeNode node in ThisSelectedNode.Nodes)
{
selectedBelow += selectedBelow + "\\" + node.Text;
}
return selcetedAbove + selectedBelow;
}
This will close the Treeview and selected nodes Text will be copied to the SelectedPath (Which is a string variable).
|