How to build function GetNodeByText for TreeView?

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

Guest

I have such one written in VB6.

Public Function GetNodeByText(colNodes As Nodes, sText As String) As Node
Dim nodEach As Node, nodResult As Node
For Each nodEach In colNodes
If nodEach.Text = sText Then
Set GetNodeByText = nodEach
Exit Function
End If
Next
End Function

But how to write in C# for .NET TreeView where each node has its own
collection of nodes and there is no total collection? It's rather difficult,
isn't it?
May someone help?

Thanks in advance.
 
You could use a function recursively. Something like:

public class NodeGetter
{
TreeNode node;

public void GetNodeByText(TreeNodeCollection nodes, string text)
{
foreach (TreeNode node in nodes)
{
if (node.Text == text)
{
this.node = node;
break;
}
if (node.Nodes.Count > 0)
GetNodeByText(node.Nodes)
}
}

public static Main()
{
NodeGetter ng = new(NodeGetter);
ng.node = null;
TreeView tv = new TreeView();
// populate tree
ng.GetNodeByText(tv.Nodes,"sometext");
if (ng.node != null)
{
// do work with ng.node
}
}
}
 

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

Back
Top