Tuesday, 18 August 2009

TreeView - Some Useful Code

Well don't know about everyone else, but I think the treeview control is one of the worst controls I have seen simple because of the way you have to code the collections and there isn't even a basic property for the index. Also the webforms version is very different from the winforms control.

Anyway, after lots of messing about here is some code you might find useful:

//Add Root with Text
TreeNode root = new TreeNode();
root.Text = "Root Text";
TreeView1.Nodes.Add(root);


//Get Index of Selected Item
int myindex = TreeView1.SelectedNode.Parent.ChildNodes.IndexOf(TreeView1.SelectedNode);


//Remove Selected Child
try
{
int myindex = TreeView1.SelectedNode.Parent.ChildNodes.IndexOf(TreeView1.SelectedNode);

string removenode = TreeView1.SelectedNode.ValuePath;

TreeNode MyNodeToDelete = TreeView1.FindNode(removenode);
MyNodeToDelete.Parent.ChildNodes.Remove(MyNodeToDelete);
}
catch (Exception ex) {

}

//Remove Parent Node
try {
int myindex = TreeView1.SelectedNode.Parent.ChildNodes.IndexOf(TreeView1.SelectedNode);
string removenode = TreeView1.SelectedNode.ValuePath;

TreeNode MyNodeToDelete = TreeView1.FindNode(removenode);
MyNodeToDelete.Parent.ChildNodes.Remove(MyNodeToDelete);

}
catch (Exception ex)
{

}




I apologize for the code formatting, I will try to rectify this as soon as I have chance.

No comments: