New to Telerik UI for WinForms? Download free 30-day trial

Find a RadTreeNode by the Value

Environment

Product Version 2018.3 911
Product RadTreeView for WinForms

Description

RadTreeView supports searching for nodes by the Text of the node:

radTreeView1.Find("Test");

It is also possible to search by a Predicate which returns an array of all nodes that match the search criteria. A common case is to look for nodes by a certain value. The following approach gives you an easy way to search the nodes by the Value property.

Search nodes by Value

treeview-find-node-by-value001

Solution

In order to find the node by a given value, it is necessary to iterate all nodes recursively and check whether their Value property matches the search pattern:

  public RadForm1()
{
    InitializeComponent();

    int cnt = 0;
    for (int i = 0; i < 5; i++)
    {
        cnt++;
        RadTreeNode node = new RadTreeNode();
        node.Text = "Node" + cnt;
        node.Value = cnt;
        this.radTreeView1.Nodes.Add(node);
        for (int j = 0; j < 5; j++)
        {
            cnt++;
            RadTreeNode childNode = new RadTreeNode();
            childNode.Text = "ChildNode" + cnt;
            childNode.Value = cnt;
            node.Nodes.Add(childNode);
            for (int k = 0; k < 3; k++)
            {
                cnt++;
                RadTreeNode grandChildNode = new RadTreeNode();
                grandChildNode.Text = "ChildNode" + cnt;
                grandChildNode.Value = cnt;
                childNode.Nodes.Add(grandChildNode);
            }
        }
    }

    object value = 12;

    RadTreeNode foundNode = FindNodeByValue(value, this.radTreeView1.Nodes);
    if (foundNode != null)
    {
        this.radTreeView1.SelectedNode = foundNode;
    }
    this.radTreeView1.ExpandAll();
}

private RadTreeNode FindNodeByValue(object value, Telerik.WinControls.UI.RadTreeNodeCollection nodes)
{
    foreach (RadTreeNode node in nodes)
    {
        if (node.Value.Equals(value))
        {
            return node;
        }
        else
        {
            RadTreeNode n = FindNodeByValue(value, node.Nodes);
            if (n != null)
            {
                return n;
            }
        }
    }

    return null;
}