Reputation: 3
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"
Upvotes: 0
Views: 3146
Reputation: 4173
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");
Upvotes: 2