Retrieve a TreeNode by Name
Robert McLaws listed some of his peeves about WinForms 2.0. A lot of them I agree with, including the fact that ToolStrips and MenuStrips don't seem to have an ImageIndex pointing into an ImageList any more (you have to use the "Image" property on each item to point to an image resource nowadays). However, the one about not being able to get a TreeNode by name is not quite true. Here's a method I use in Comicster (slightly modified to make it usable to other programs):
public TreeNode GetNodeByName(TreeView treeView, string key) { TreeNode[] nodes = treeView.Nodes.Find(key, true); return nodes.Length > 0 ? nodes[0] : null; }
Sure, it's not 'built in' ... but at least TreeNodeCollection has a 'Find' method that lets you easily search the nodes by name. Hope this helps!
Comments
# euan
25/06/2005 4:38 PM
Could you do that blog in vb.net please?
# mabster
25/06/2005 5:28 PM
Couldn't be that different, could it? I don't really know vb.net's syntax.
# euan
26/06/2005 10:05 PM
Ah it is but I was just joking.
I can get the jist of C# code anyway. Its similar... sort of.
# cindy
8/05/2006 5:00 AM
It does not have this function
# mabster
8/05/2006 7:08 AM
No - this is a method you need to write yourself. "GetNodeByName" isn't a method of TreeNode.
# Saheli
19/09/2006 5:50 PM
How to get the find method in treenodecollection.
# mabster
19/09/2006 6:07 PM
Hi Saheli,
I'm assuming that's an oddly-phrased question from a non-English speaker, which translates as, "How to I get the 'Find' method in TreeNodeCollection?"
Well ... the answer is that you don't have to "get" it - it's part of the class. There's no magic involved. Perhaps it wasn't around back in .NET 1.1 and you haven't yet moved up to 2.0?
# Andrwe
14/08/2008 8:02 PM
Thanks this works beautifully!!
# raju
5/01/2012 2:59 PM
not working DriveInfo[] drives= DriveInfo.GetDrives();
foreach (DriveInfo d in drives)
{
TreeNode root = new TreeNode(d.Name);
root.Tag = d.Name;
root.Nodes.Add(new TreeNode());
treeView1.Nodes.Add(root);
}
/***** to set default directory **********/
//TreeNode node = new TreeNode(@"C:\");
//treeView1.SelectedNode = node;
TreeNode[] nodes = treeView1.Nodes.Find(@"C:\", true);
if (nodes.Length > 0)
{
treeView1.SelectedNode = nodes[0];
treeView1.SelectedNode.Expand();
}