TreeView Class

Definition

Displays a hierarchical collection of labeled items, each represented by a TreeNode.

[System.Runtime.InteropServices.ClassInterface(System.Runtime.InteropServices.ClassInterfaceType.AutoDispatch)]
[System.Runtime.InteropServices.ComVisible(true)]
[System.Windows.Forms.Docking(System.Windows.Forms.DockingBehavior.Ask)]
public class TreeView : System.Windows.Forms.Control
Inheritance
Derived
System.ComponentModel.Design.ObjectSelectorEditor.Selector
Attributes

Inherited Members

System.ComponentModel.Component

System.MarshalByRefObject

System.Object

System.Windows.Forms.Control

Examples

The following code example demonstrates the use of the TreeView control.

// Populates a TreeView control with example nodes. 
private void InitializeTreeView()
{
    treeView1.BeginUpdate();
    treeView1.Nodes.Add("Parent");
    treeView1.Nodes[0].Nodes.Add("Child 1");
    treeView1.Nodes[0].Nodes.Add("Child 2");
    treeView1.Nodes[0].Nodes[1].Nodes.Add("Grandchild");
    treeView1.Nodes[0].Nodes[1].Nodes[0].Nodes.Add("Great Grandchild");
    treeView1.EndUpdate();
}
' Populates a TreeView control with example nodes. 
Private Sub InitializeTreeView()
    treeView1.BeginUpdate()
    treeView1.Nodes.Add("Parent")
    treeView1.Nodes(0).Nodes.Add("Child 1")
    treeView1.Nodes(0).Nodes.Add("Child 2")
    treeView1.Nodes(0).Nodes(1).Nodes.Add("Grandchild")
    treeView1.Nodes(0).Nodes(1).Nodes(0).Nodes.Add("Great Grandchild")
    treeView1.EndUpdate()
End Sub

The following, more complex code example displays customer information in a TreeView control. The root tree nodes display customer names, and the child tree nodes display the order numbers assigned to each customer. In this example, 1,000 customers are displayed with 15 orders each. The repainting of the TreeView is suppressed by using the BeginUpdate and EndUpdate methods, and a wait Cursor is displayed while the TreeView creates and paints the TreeNode objects. This example requires that you have a Customer object that can hold a collection of Order objects. It also requires that you have a cursor file that is named MyWait.cur in the application directory and that you have created an instance of a TreeView control on a Form.

// The basic Customer class.
ref class Customer: public System::Object
{
private:
   String^ custName;

protected:
   ArrayList^ custOrders;

public:
   Customer( String^ customername )
   {
      custName = "";
      custOrders = gcnew ArrayList;
      this->custName = customername;
   }


   property String^ CustomerName 
   {
      String^ get()
      {
         return this->custName;
      }

      void set( String^ value )
      {
         this->custName = value;
      }

   }

   property ArrayList^ CustomerOrders 
   {
      ArrayList^ get()
      {
         return this->custOrders;
      }

   }

};


// End Customer class
// The basic customer Order class.
ref class Order: public System::Object
{
private:
   String^ ordID;

public:
   Order( String^ orderid )
   {
      ordID = "";
      this->ordID = orderid;
   }


   property String^ OrderID 
   {
      String^ get()
      {
         return this->ordID;
      }

      void set( String^ value )
      {
         this->ordID = value;
      }

   }

};
// End Order class



void FillMyTreeView()
{
   // Add customers to the ArrayList of Customer objects.
   for ( int x = 0; x < 1000; x++ )
   {
      customerArray->Add( gcnew Customer( "Customer " + x ) );
   }
   
   // Add orders to each Customer object in the ArrayList.
   IEnumerator^ myEnum = customerArray->GetEnumerator();
   while ( myEnum->MoveNext() )
   {
      Customer^ customer1 = safe_cast<Customer^>(myEnum->Current);
      for ( int y = 0; y < 15; y++ )
      {
         customer1->CustomerOrders->Add( gcnew Order( "Order " + y ) );
      }
   }

   // Display a wait cursor while the TreeNodes are being created.
   ::Cursor::Current = gcnew System::Windows::Forms::Cursor( "MyWait.cur" );
   
   // Suppress repainting the TreeView until all the objects have been created.
   treeView1->BeginUpdate();
   
   // Clear the TreeView each time the method is called.
   treeView1->Nodes->Clear();
   
   // Add a root TreeNode for each Customer object in the ArrayList.
   myEnum = customerArray->GetEnumerator();
   while ( myEnum->MoveNext() )
   {
      Customer^ customer2 = safe_cast<Customer^>(myEnum->Current);
      treeView1->Nodes->Add( gcnew TreeNode( customer2->CustomerName ) );
      
      // Add a child treenode for each Order object in the current Customer object.
      IEnumerator^ myEnum = customer2->CustomerOrders->GetEnumerator();
      while ( myEnum->MoveNext() )
      {
         Order^ order1 = safe_cast<Order^>(myEnum->Current);
         treeView1->Nodes[ customerArray->IndexOf( customer2 ) ]->Nodes->Add( gcnew TreeNode( customer2->CustomerName + "." + order1->OrderID ) );
      }
   }
   
   // Reset the cursor to the default for all controls.
   ::Cursor::Current = Cursors::Default;
   
   // Begin repainting the TreeView.
   treeView1->EndUpdate();
}

// The basic Customer class.
public class Customer : System.Object
{
   private string custName = "";
   protected ArrayList custOrders = new ArrayList();

   public Customer(string customername)
   {
      this.custName = customername;
   }

   public string CustomerName
   {      
      get{return this.custName;}
      set{this.custName = value;}
   }

   public ArrayList CustomerOrders 
   {
      get{return this.custOrders;}
   }

} // End Customer class 


// The basic customer Order class.
public class Order : System.Object
{
   private string ordID = "";

   public Order(string orderid)
   {
      this.ordID = orderid;
   }

   public string OrderID
   {      
      get{return this.ordID;}
      set{this.ordID = value;}
   }

} // End Order class

// Create a new ArrayList to hold the Customer objects.
private ArrayList customerArray = new ArrayList(); 

private void FillMyTreeView()
{
   // Add customers to the ArrayList of Customer objects.
   for(int x=0; x<1000; x++)
   {
      customerArray.Add(new Customer("Customer" + x.ToString()));
   }

   // Add orders to each Customer object in the ArrayList.
   foreach(Customer customer1 in customerArray)
   {
      for(int y=0; y<15; y++)
      {
         customer1.CustomerOrders.Add(new Order("Order" + y.ToString()));    
      }
   }

   // Display a wait cursor while the TreeNodes are being created.
   Cursor.Current = new Cursor("MyWait.cur");
        
   // Suppress repainting the TreeView until all the objects have been created.
   treeView1.BeginUpdate();

   // Clear the TreeView each time the method is called.
   treeView1.Nodes.Clear();

   // Add a root TreeNode for each Customer object in the ArrayList.
   foreach(Customer customer2 in customerArray)
   {
      treeView1.Nodes.Add(new TreeNode(customer2.CustomerName));
          
      // Add a child treenode for each Order object in the current Customer object.
      foreach(Order order1 in customer2.CustomerOrders)
      {
         treeView1.Nodes[customerArray.IndexOf(customer2)].Nodes.Add(
           new TreeNode(customer2.CustomerName + "." + order1.OrderID));
      }
   }

   // Reset the cursor to the default for all controls.
   Cursor.Current = Cursors.Default;

   // Begin repainting the TreeView.
   treeView1.EndUpdate();
}
Public Class Customer
   Inherits [Object]
   Private custName As String = ""
   Friend custOrders As New ArrayList()

   Public Sub New(ByVal customername As String)
      Me.custName = customername
   End Sub

   Public Property CustomerName() As String
      Get
         Return Me.custName
      End Get
      Set(ByVal Value As String)
         Me.custName = Value
      End Set
   End Property

   Public ReadOnly Property CustomerOrders() As ArrayList
      Get
         Return Me.custOrders
      End Get
   End Property
End Class 'End Customer class


Public Class Order
   Inherits [Object]
   Private ordID As String

   Public Sub New(ByVal orderid As String)
      Me.ordID = orderid
   End Sub 'New

   Public Property OrderID() As String
      Get
         Return Me.ordID
      End Get
      Set(ByVal Value As String)
         Me.ordID = Value
      End Set
   End Property
End Class ' End Order class

' Create a new ArrayList to hold the Customer objects.
Private customerArray As New ArrayList()

Private Sub FillMyTreeView()
   ' Add customers to the ArrayList of Customer objects.
   Dim x As Integer
   For x = 0 To 999
      customerArray.Add(New Customer("Customer" + x.ToString()))
   Next x

   ' Add orders to each Customer object in the ArrayList.
   Dim customer1 As Customer
   For Each customer1 In customerArray
      Dim y As Integer
      For y = 0 To 14
         customer1.CustomerOrders.Add(New Order("Order" + y.ToString()))
      Next y
   Next customer1

   ' Display a wait cursor while the TreeNodes are being created.
   Cursor.Current = New Cursor("MyWait.cur")

   ' Suppress repainting the TreeView until all the objects have been created.
   treeView1.BeginUpdate()

   ' Clear the TreeView each time the method is called.
   treeView1.Nodes.Clear()

   ' Add a root TreeNode for each Customer object in the ArrayList.
   Dim customer2 As Customer
   For Each customer2 In customerArray
      treeView1.Nodes.Add(New TreeNode(customer2.CustomerName))

      ' Add a child TreeNode for each Order object in the current Customer object.
      Dim order1 As Order
      For Each order1 In customer2.CustomerOrders
         treeView1.Nodes(customerArray.IndexOf(customer2)).Nodes.Add( _
    New TreeNode(customer2.CustomerName + "." + order1.OrderID))
      Next order1
   Next customer2

   ' Reset the cursor to the default for all controls.
   Cursor.Current = System.Windows.Forms.Cursors.Default

   ' Begin repainting the TreeView.
   treeView1.EndUpdate()
End Sub 'FillMyTreeView

Remarks

The Nodes collection holds all the TreeNode objects that are assigned to the TreeView control. The tree nodes in this collection are referred to as the root tree nodes. Any tree node that is subsequently added to a root tree node is referred to as a child node. Because each TreeNode can contain a collection of other TreeNode objects, you might find it difficult to determine your location in the tree structure when you iterate through the collection. You can parse the TreeNode.FullPath string by using the PathSeparator string value to determine where a TreeNode label begins and ends.

You can display images next to the tree nodes by assigning an ImageList to the ImageList property and referencing the index value of an Image in the ImageList to assign that Image. Use the following properties to assign images:

The images referenced by the ImageIndex and SelectedImageIndex property values are the default images displayed by all the tree nodes that are assigned to the Nodes collection. Individual tree nodes can override the default images by setting the TreeNode.ImageIndex and TreeNode.SelectedImageIndex properties.

The state images displayed in the TreeView are 16 x 16 pixels by default. Setting the ImageSize property of the StateImageList will have no effect on how the images are displayed. However, the state images are resized according to the system DPI setting when the app.config file contains the following entry:

<appSettings>  
  <add key="EnableWindowsFormsHighDpiAutoResizing" value="true" />  
</appSettings>  

Tree nodes can be expanded to display the next level of child tree nodes. The user can expand the TreeNode by clicking the plus-sign (+) button, if one is displayed next to the TreeNode, or you can expand the TreeNode by calling the TreeNode.Expand method. To expand all the child tree node levels in the Nodes collection, call the ExpandAll method. You can collapse the child TreeNode level by calling the TreeNode.Collapse method, or the user can press the minus-sign (-) button, if one is displayed next to the TreeNode. You can also call the TreeNode.Toggle method to alternate between the expanded and collapsed states.

Tree nodes can optionally display check boxes. To display the check boxes, set the CheckBoxes property of the TreeView to true. The Checked property is set to true for tree nodes that are in a checked state.

Note

Setting the TreeNode.Checked property from within the BeforeCheck or AfterCheck event causes the event to be raised multiple times and can result in unexpected behavior. For example, you might set the Checked property in the event handler when you are recursively updating the child nodes so that the user does not have to expand and check each one individually. To prevent the event from being raised multiple times, add logic to your event handler that only executes your recursive code if the Action property of the TreeViewEventArgs is not set to TreeViewAction.Unknown. For an example of how to do this, see the Example section of the AfterCheck or BeforeCheck events.

You can change the appearance of the TreeView control by setting some of its display and style properties. Setting ShowPlusMinus to true displays a plus-sign or minus-sign button next to each TreeNode that can be expanded or collapsed, respectively. Setting the ShowRootLines property to true causes the TreeView to display lines that join all the root tree nodes together. You can display lines that connect child tree nodes to their root node by setting the ShowLines property to true. Setting the HotTracking property to true changes the appearance of the tree node labels as the mouse pointer passes over them. When hot-tracked, the tree node labels take on the appearance of a hyperlink. You can also completely customize the appearance of the TreeView control. To do this, set the DrawMode property to a value other than TreeViewDrawMode.Normal and handle the DrawNode event.

Note

When setting the CheckBoxes, Scrollable, ImageIndex, and SelectedImageIndex properties at run time, the TreeView handle is recreated (see Control.RecreateHandle) to update the control's appearance. This causes all tree nodes to be collapsed, except for the selected TreeNode.

Constructors

TreeView()

Initializes a new instance of the TreeView class.

Properties

BackColor

Gets or sets the background color for the control.

BackgroundImage

Gets or set the background image for the TreeView control.

BackgroundImageLayout

Gets or sets the layout of the background image for the TreeView control.

BorderStyle

Gets or sets the border style of the tree view control.

CheckBoxes

Gets or sets a value indicating whether check boxes are displayed next to the tree nodes in the tree view control.

CreateParams

Gets the required creation parameters when the control handle is created.

DefaultSize

Gets the default size of the control.

DoubleBuffered

Gets or sets a value indicating whether the control should redraw its surface using a secondary buffer. The DoubleBuffered property does not affect the TreeView control.

DrawMode

Gets or sets the mode in which the control is drawn.

ForeColor

Gets or sets the foreground color of the control.

FullRowSelect

Gets or sets a value indicating whether the selection highlight spans the width of the tree view control.

HideSelection

Gets or sets a value indicating whether the selected tree node remains highlighted even when the tree view has lost the focus.

HotTracking

Gets or sets a value indicating whether a tree node label takes on the appearance of a hyperlink as the mouse pointer passes over it.

ImageIndex

Gets or sets the image-list index value of the default image that is displayed by the tree nodes.

ImageKey

Gets or sets the key of the default image for each node in the TreeView control when it is in an unselected state.

ImageList

Gets or sets the ImageList that contains the Image objects that are used by the tree nodes.

Indent

Gets or sets the distance to indent each child tree node level.

ItemHeight

Gets or sets the height of each tree node in the tree view control.

LabelEdit

Gets or sets a value indicating whether the label text of the tree nodes can be edited.

LineColor

Gets or sets the color of the lines connecting the nodes of the TreeView control.

Nodes

Gets the collection of tree nodes that are assigned to the tree view control.

Padding

Gets or sets the spacing between the TreeView control's contents and its edges.

PathSeparator

Gets or sets the delimiter string that the tree node path uses.

RightToLeftLayout

Gets or sets a value that indicates whether the TreeView should be laid out from right-to-left.

Scrollable

Gets or sets a value indicating whether the tree view control displays scroll bars when they are needed.

SelectedImageIndex

Gets or sets the image list index value of the image that is displayed when a tree node is selected.

SelectedImageKey

Gets or sets the key of the default image shown when a TreeNode is in a selected state.

SelectedNode

Gets or sets the tree node that is currently selected in the tree view control.

ShowLines

Gets or sets a value indicating whether lines are drawn between tree nodes in the tree view control.

ShowNodeToolTips

Gets or sets a value indicating ToolTips are shown when the mouse pointer hovers over a TreeNode.

ShowPlusMinus

Gets or sets a value indicating whether plus-sign (+) and minus-sign (-) buttons are displayed next to tree nodes that contain child tree nodes.

ShowRootLines

Gets or sets a value indicating whether lines are drawn between the tree nodes that are at the root of the tree view.

Sorted

Gets or sets a value indicating whether the tree nodes in the tree view are sorted.

StateImageList

Gets or sets the image list that is used to indicate the state of the TreeView and its nodes.

Text

Gets or sets the text of the TreeView.

TopNode

Gets or sets the first fully-visible tree node in the tree view control.

TreeViewNodeSorter

Gets or sets the implementation of IComparer to perform a custom sort of the TreeView nodes.

VisibleCount

Gets the number of tree nodes that can be fully visible in the tree view control.

Methods

BeginUpdate()

Disables any redrawing of the tree view.

CollapseAll()

Collapses all the tree nodes.

CreateHandle()

Creates a handle for the control.

Dispose(Boolean)

Releases the unmanaged resources used by the TreeView and optionally releases the managed resources.

EndUpdate()

Enables the redrawing of the tree view.

ExpandAll()

Expands all the tree nodes.

GetItemRenderStyles(TreeNode, Int32)

Returns an OwnerDrawPropertyBag for the specified TreeNode.

GetNodeAt(Point)

Retrieves the tree node that is at the specified point.

GetNodeAt(Int32, Int32)

Retrieves the tree node at the point with the specified coordinates.

GetNodeCount(Boolean)

Retrieves the number of tree nodes, optionally including those in all subtrees, assigned to the tree view control.

HitTest(Int32, Int32)

Provides node information, given x- and y-coordinates.

HitTest(Point)

Provides node information, given a point.

IsInputKey(Keys)

Determines whether the specified key is a regular input key or a special key that requires preprocessing.

OnAfterCheck(TreeViewEventArgs)

Raises the AfterCheck event.

OnAfterCollapse(TreeViewEventArgs)

Raises the AfterCollapse event.

OnAfterExpand(TreeViewEventArgs)

Raises the AfterExpand event.

OnAfterLabelEdit(NodeLabelEditEventArgs)

Raises the AfterLabelEdit event.

OnAfterSelect(TreeViewEventArgs)

Raises the AfterSelect event.

OnBeforeCheck(TreeViewCancelEventArgs)

Raises the BeforeCheck event.

OnBeforeCollapse(TreeViewCancelEventArgs)

Raises the BeforeCollapse event.

OnBeforeExpand(TreeViewCancelEventArgs)

Raises the BeforeExpand event.

OnBeforeLabelEdit(NodeLabelEditEventArgs)

Raises the BeforeLabelEdit event.

OnBeforeSelect(TreeViewCancelEventArgs)

Raises the BeforeSelect event.

OnDrawNode(DrawTreeNodeEventArgs)

Raises the DrawNode event.

OnHandleCreated(EventArgs)

Overrides OnHandleCreated(EventArgs).

OnHandleDestroyed(EventArgs)

Overrides OnHandleDestroyed(EventArgs).

OnItemDrag(ItemDragEventArgs)

Raises the ItemDrag event.

OnKeyDown(KeyEventArgs)

Raises the KeyDown event.

OnKeyPress(KeyPressEventArgs)

Raises the KeyPress event.

OnKeyUp(KeyEventArgs)

Overrides OnKeyUp(KeyEventArgs).

OnMouseHover(EventArgs)

Raises the MouseHover event.

OnMouseLeave(EventArgs)

Raises the MouseLeave event.

OnNodeMouseClick(TreeNodeMouseClickEventArgs)

Raises the NodeMouseClick event.

OnNodeMouseDoubleClick(TreeNodeMouseClickEventArgs)

Raises the NodeMouseDoubleClick event.

OnNodeMouseHover(TreeNodeMouseHoverEventArgs)

Raises the NodeMouseHover event.

OnRightToLeftLayoutChanged(EventArgs)

Raises the RightToLeftLayoutChanged event.

Sort()

Sorts the items in TreeView control.

ToString()

Returns a String containing the name of the Component, if any. This method should not be overridden.

WndProc(Message)

Overrides WndProc(Message).

Events

AfterCheck

Occurs after the tree node check box is checked.

AfterCollapse

Occurs after the tree node is collapsed.

AfterExpand

Occurs after the tree node is expanded.

AfterLabelEdit

Occurs after the tree node label text is edited.

AfterSelect

Occurs after the tree node is selected.

BackgroundImageChanged

Occurs when the BackgroundImage property changes.

BackgroundImageLayoutChanged

Occurs when the BackgroundImageLayout property changes.

BeforeCheck

Occurs before the tree node check box is checked.

BeforeCollapse

Occurs before the tree node is collapsed.

BeforeExpand

Occurs before the tree node is expanded.

BeforeLabelEdit

Occurs before the tree node label text is edited.

BeforeSelect

Occurs before the tree node is selected.

DrawNode

Occurs when a TreeView is drawn and the DrawMode property is set to a TreeViewDrawMode value other than Normal.

ItemDrag

Occurs when the user begins dragging a node.

NodeMouseClick

Occurs when the user clicks a TreeNode with the mouse.

NodeMouseDoubleClick

Occurs when the user double-clicks a TreeNode with the mouse.

NodeMouseHover

Occurs when the mouse hovers over a TreeNode.

PaddingChanged

Occurs when the value of the Padding property changes.

Paint

Occurs when the TreeView is drawn.

RightToLeftLayoutChanged

Occurs when the value of the RightToLeftLayout property changes.

TextChanged

Occurs when the Text property changes.