0

I have a TreeView Control in my aspx page.

Each TreeNode has a Text & Value property in that.

for e.g.

TreeView Tr_View = new TreeView();
                    TreeNode TrNode=new TreeNode("ABC","1");
                    Tr_View.Nodes.Add(TrNode);
                    TrNode = new TreeNode("DEF", "5");
                    Tr_View.Nodes.Add(TrNode);
                    TrNode = new TreeNode("GHI", "9");
                    Tr_View.Nodes.Add(TrNode);
                    TrNode = new TreeNode("JKL", "11");
                    Tr_View.Nodes.Add(TrNode);

The Problem is that I want to select 3rd node on the basis of its value "9"

1 Answer 1

2

Use following code to find node with value "9" and select it:

var node = Tr_View.FindNode("9");
node.Select();

Note that "9" here is a path to node. So if you will have nodes at non-root level, you will need to specify full path, like "root.child.9".

If you don't have a full path, probably the best way to find a node based on node value would be to traverse all tree nodes:

using System.Linq;
using System.Collections.Generic;
...
IEnumerable<TreeNode> GetAllNodes()
{
  Stack<TreeNode> roots = new Stack<TreeNode>(Tr_View.Nodes);
  while(roots.Count > 0)
  {
    var node = roots.Pop();
    foreach (var child in node.ChildNodes)
      roots.Push(child);

    yield return node;
  }
}
...
var allNodesWithValue9 = GetAllNodes().Where(n => n.Value == "9");
Sign up to request clarification or add additional context in comments.

1 Comment

.SelectedNode is a READ ONLY property. Your first solution doesn't work

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.