TreeNodeCollection.Count Property


The .NET API Reference documentation has a new home. Visit the .NET API Browser on to see the new experience.

Gets the total number of TreeNode objects in the collection.

Namespace:   System.Windows.Forms
Assembly:  System.Windows.Forms (in System.Windows.Forms.dll)

public int Count { get; }

Property Value

Type: System.Int32

The total number of TreeNode objects in the collection.

The Count property holds the number of TreeNode objects assigned to the collection. You can use the Count property value as the upper bounds of a loop to iterate through a collection.


Because the index value of a collection is a zero-based index, you must subtract one from the looping variable. If you do not account for this, you will exceed the upper bounds of the collection and throw an IndexOutOfRangeException exception.

The following code example displays the number of TreeNode objects in a TreeNodeCollection, copies the contents of the collection to an Object array, and displays a list of the tree nodes in a Label control. This example requires that you have a TreeView with at least one TreeNode in its TreeNodeCollection, and a Label control on a Form.

private void CopyTreeNodes()
   // Get the collection of TreeNodes.
   TreeNodeCollection myNodeCollection = myTreeView.Nodes;
   int myCount = myNodeCollection.Count;

   myLabel.Text += "Number of nodes in the collection :" + myCount;
   myLabel.Text += "\n\nElements of the Array after Copying from the collection :\n";
   // Create an Object array.
   Object[] myArray = new Object[myCount];
   // Copy the collection into an array.
   for(int i=0; i<myArray.Length; i++)
      myLabel.Text += ((TreeNode)myArray[i]).Text + "\n";

.NET Framework
Available since 1.1
Return to top