|
-
Dec 13th, 2007, 04:54 AM
#1
Thread Starter
PowerPoster
Recursive method help
I am trying to go through each and every single treenode in a treeview.
I want to be able to return a treenode, or null, if a specific object has been found. how can I do this? I feel like i've lost all my knowledge!
private TreeNode GetObjectFromTreeView(TreeNode startingNode, MyObject objectToMatch)
{
foreach(TreeNode currentNode in startingNode.Nodes)
{
if (currentNode.Tag != null && currentNode.Tag.GetType() == typeof(MyObject))
{
return currentNode;
}
return this.GetObjectFromTreeView(currentNode, objectToMatch);
}
return null;
}
-
Dec 13th, 2007, 07:25 AM
#2
Re: Recursive method help
You're checking the type of the object (which is sensible), but not its value. If you have more than one tag of the same type then you'll simply stop at the first one, by the look of it.
-
Dec 13th, 2007, 08:02 AM
#3
Re: Recursive method help
Easier than using GetType:
Code:
currentNode.Tag is MyObject
-
Dec 13th, 2007, 08:04 AM
#4
Re: Recursive method help
Actually, you don't need to check its type: just compare references.
Code:
if (currentNode.Tag != null && Object.ReferenceEquals(currentNode.Tag, objectToMatch))
-
Dec 13th, 2007, 06:14 PM
#5
Re: Recursive method help
CSharp Code:
private TreeNode GetObjectFromTreeView(TreeNode startingNode, MyObject objectToMatch)
{
TreeNode result = null;
foreach (TreeNode currentNode in startingNode.Nodes)
{
if (currentNode.Tag == objectToMatch)
{
result = currentNode;
break;
}
result = this.GetObjectFromTreeView(currentNode, objectToMatch);
if (result != null)
{
break;
}
}
return result;
}
That code will not work for value types but it will for reference types.
Last edited by jmcilhinney; Dec 13th, 2007 at 06:28 PM.
Posting Permissions
- You may not post new threads
- You may not post replies
- You may not post attachments
- You may not edit your posts
-
Forum Rules
|
Click Here to Expand Forum to Full Width
|