---
title: "How to get index of all the nodes in a TreeView?"  
description: "How to get index of all the nodes in a TreeView?"  
author: "David Miller"  
published: 2014-11-21  
updated: 2014-11-21  
canonical: https://www.mindstick.com/forum/12671/how-to-get-index-of-all-the-nodes-in-a-treeview  
category: "asp.net"  
tags: ["c#", ".net"]  
reading_time: 1 minute  

---

# How to get index of all the nodes in a TreeView?

I tried using:

TreeNode [node](https://www.mindstick.com/forum/161418/what-is-node-js-and-how-does-it-work) = TreeView1.FindNode()

but it only finds [root](https://answers.mindstick.com/qa/49855/tell-me-what-is-root-port-in-spanning-tree-protocol) [nodes](https://www.mindstick.com/news/2242/on-thursday-google-cloud-announced-the-debut-of-its-own-node-hosting-service-for-web3-developers). It is not able to find Child Nodes.

I want to get [index](https://www.mindstick.com/blog/198/index-in-sql-server) of all the nodes and after that I want to use above [code](https://yourviews.mindstick.com/view/85458/alan-turing-the-mastermind-behind-cracking-the-enigma-code-during-world-war-ii) to find nodes by index and [Check](https://yourviews.mindstick.com/story/2248/never-forget-to-check-these-specifications-before-buying-a-mobile-phone) the Checkbox.

I tried using [foreach](https://www.mindstick.com/forum/33870/how-parallel-foreach-works-internally) to iterate through all the nodes, but I am not able to find child nodes and index.

I am using [Visual Studio](https://www.mindstick.com/articles/12378/visual-studio-for-mac-is-out-of-beta-preview-now-officially-available) 2013.

## Replies

### Reply by Mark Devid

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.


---

Original Source: https://www.mindstick.com/forum/12671/how-to-get-index-of-all-the-nodes-in-a-treeview

Copyright © MindStick Software Pvt. Ltd. This Markdown version is provided for developers, AI systems, and offline reading.
