Home > DeveloperSection > Forums > How to get index of all the nodes in a TreeView?
David Miller

Total Post:30

Points:210
Posted on    November-21-2014 12:44 AM

 ASP.Net C#  .NET 
Ratings:


 1 Reply(s)
 681  View(s)
Rate this:

I tried using:

TreeNode node = TreeView1.FindNode()

but it only finds root nodes. It is not able to find Child Nodes.

I want to get index of all the nodes and after that I want to use above code to find nodes by index and Check the Checkbox.

I tried using foreach to iterate through all the nodes, but I am not able to find child nodes and index.

I am using Visual Studio 2013.



Mark Devid
Mark Devid

Total Post:101

Points:707
Posted on    November-21-2014 10:29 PM

The following method allows you to traverse through a tree:

public static IEnumerable<T> Traverse<T>(

    this IEnumerable<T> source

    , Func<T, IEnumerable<T>> childrenSelector)

{

    var stack = new Stack<T>(source);

    while (stack.Any())

    {

        var next = stack.Pop();

        yield return next;

        foreach (var child in childrenSelector(next))

            stack.Push(child);

    }

}

Using this you can write:

var allNodes = new[]{root}.Traverse(node => node.Nodes);

You can then do whatever you want with the sequence of all of the nodes in the whole tree and do whatever you want with them.

 


Modified On Jun-26-2016 11:25:49 PM

Don't want to miss updates? Please click the below button!

Follow MindStick