TreeNodes search

A

Alan T

I want to search the whole tree of a root node if one node has a tag value
is matched.

I have added tree nodes into a tree view with tag value is assigned to each
node.

If I want to find out the node has tag value say 10, how do I search thro'
the whole tree ?
 
M

Marcin Hoppe

Alan said:
I want to search the whole tree of a root node if one node has a tag value
is matched.

I have added tree nodes into a tree view with tag value is assigned to each
node.

If I want to find out the node has tag value say 10, how do I search thro'
the whole tree ?

The simplest idea is to search the tree recursively:

private TreeNode SearchNodes(TreeNodeCollection nodes)
{
TreeNode result = null;

foreach(TreeNode node in nodes)
{
// Here check the search condition.
// Sample:
if(node.Tag.ToString() == "10")
{
result = node;
}
else
{
result = SearchNodes(node.Nodes);
}

if(result != null)
{
break;
}
}

return result;
}

private TreeNode SearchTreeView(TreeView view)
{
return SearchNodes(view.Nodes);
}

Best regards!
Marcin
 
T

Tom Spink

Alan said:
I want to search the whole tree of a root node if one node has a tag value
is matched.

I have added tree nodes into a tree view with tag value is assigned to
each node.

If I want to find out the node has tag value say 10, how do I search thro'
the whole tree ?

Hi Alan,

You need a recursive algorithm:

///
private TreeNode FindNodeWithTag ( TreeNodeCollection nodes, object tag )
{
foreach ( TreeNode node in nodes )
{
if ( node.Tag == tag )
return node;

TreeNode candidate = FindNodeWithTag( node.Nodes, tag );

if ( candidate != null )
return candidate;
}

return null;
}
///

Then, you call it by passing in the collection of nodes from your treeview,
and the tag you want to search for. It will return the first node that
matches that tag.
 
A

Alan T

Hi I got an exception here:

private TreeNode SearchNode(TreeNodeCollection aNodes, int aId)

{

TreeNode result = null;


foreach ( TreeNode node in aNodes )

{

if (node.Tag.ToString() == aId.ToString()) <--- exception

{

return node;

}

The exception is "The object reference is not set to an instance of object"
 
M

Marcin Hoppe

Alan said:
if (node.Tag.ToString() == aId.ToString()) <--- exception

The exception is "The object reference is not set to an instance of object"

Apparently your nodes have the Tag property set to null. I assumed that
you use it to store some information. If you store information in the
Tag property of only some of your nodes, just check it before the
comparison:

if(node.Tag != null)
{
if(node.Tag.ToString() == aId.ToString())
{
return node;
}
}

Best regards!
Marcin
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top