How to select treenode in treeview by name?

  • Thread starter Thread starter Guest
  • Start date Start date
G

Guest

I have a treeview that I am continually added nodes to. Each time a new node
is added I would like to select that node.

Is this possible? I have looked at selectedNode, but I don't know how to
point that at a given node using the nodes name.

I have the nodes name and it's parents name. Does anyone know a good way to
find the node based on this information?

Thanks a bunch.
 
I have a treeview that I am continually added nodes to. Each time a new node
is added I would like to select that node.

The easiest way to do that is probably

TreeNode node = // ... create node via Nodes.Add or whatever
yourTreeView.SelectedNode = node;

Is this possible? I have looked at selectedNode, but I don't know how to
point that at a given node using the nodes name.

I have the nodes name and it's parents name. Does anyone know a good way to
find the node based on this information?

TreeNodes don't have names. I'm not sure if you mean the name of the
variable you use to reference the nodes or the Text property of the
node. Either way, it's probably easier to do as above.



Mattias
 
Thanks for the response.

When I said name before I did mean the treeNode.text and treeNode.parent.text.

My question is how do I use the above mentioned information to get a new
treeNode object that I can select.

For Example

TreeNode myTreeNode = "how do I create treenode based on parent.text and
node.text?"
myTreeView.selectedNode = myTreeNode;
 
When I said name before I did mean the treeNode.text and treeNode.parent.text.

Ah, ok.

My question is how do I use the above mentioned information to get a new
treeNode object that I can select.

If all nodes have unique Text properties, you could maintain a
Hashtable that maps Text to TreeNode and use that to look up the
parent node.



Mattias
 
I wrote two functions for a project that I did that find the TreeNode base
on Node.Text or Node.Tag.

TopNode - Node you want the search to start

public static TreeNode TreeNodeFindTag(TreeNode TopNode, string Tag)
{
//Recursive find
foreach(TreeNode node in TopNode.Nodes)
{
if(node.Tag.ToString() == Tag)
return node;


//Search its childrens
TreeNode nodeChild = TreeNodeFindTag(node,Tag);
if(nodeChild != null) return nodeChild;
}
return null;
}

public static TreeNode TreeNodeFindText(TreeNode TopNode, string Text)
{
foreach(TreeNode node in TopNode.Nodes)
{
if(node.Text.Trim().ToUpper() == Text.Trim().ToUpper())
return node;
//Recursive find
TreeNode nodeChild = TreeNodeFindText(node,Text);
if(nodeChild != null) return nodeChild;
}
return null;
}

David
 
Back
Top