This documentation is archived and is not being maintained.

TreeNodeCollection.Count Property

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

Supported in: 4, 3.5, 3.0, 2.0, 1.1, 1.0

.NET Framework Client Profile

Supported in: 4, 3.5 SP1

Windows 7, Windows Vista SP1 or later, Windows XP SP3, Windows XP SP2 x64 Edition, Windows Server 2008 (Server Core not supported), Windows Server 2008 R2 (Server Core supported with SP1 or later), Windows Server 2003 SP2

The .NET Framework does not support all versions of every platform. For a list of the supported versions, see .NET Framework System Requirements.