Free Resources from FMS

Additional Resources

 

Thank you! Thank you! I just finished reading this document, which was part of a link in the recent Buzz newsletter. I have printed it for others to read, especially those skeptical on the powers of Access and its capabilities.

Darren D.

 

Free Catalog

 

Using the MouseDown event with Windows Forms Treeview controls

Provided by: Dan Haught, FMS Executive Vice President

Overview

This example code shows two important treeview concepts:
  1. How to get a handle to the node that was clicked on.
  2. How to set focus to a node when it is right-clicked.

Example

To use this code, create a new Windows Form object and add a treeview control. Add the following code to the formís class. Then hook up the MouseDown event to the appropriate code (VB.NET or C#).

    ' VB

    Private Sub TreeView1_MouseDown( _

    ByVal sender As System.Object, _

    ByVal e As System.Windows.Forms.MouseEventArgs) _

    Handles TreeView1.MouseDown

   

        Dim NodeClicked As TreeNode

   

        ' Get the node clicked on

        NodeClicked = Me.TreeView1.GetNodeAt(e.X, e.Y)

   

        ' Was a node clicked on

        If Not NodeClicked Is Nothing Then

            Console.WriteLine("Node is: " & NodeClicked.Text)

        Else

            Console.WriteLine("No node clicked.")

        End If

 

        ' By default, right-clicking on a node does not set

        ' focus to that node. This is especially important when

        ' you want to use a ContextMenu control and associate

        ' it with a TreeView.  This code shows how to do it.

        If e.Button = MouseButtons.Right Then

            Me.TreeView1.SelectedNode = NodeClicked

        End If

   

    End Sub

 

    // C#

    private void TreeViewMouseDown (object sender, MouseEventArgs e)

    {

        TreeNode nodeClicked;

        // Get the node clicked on

        nodeClicked = this.TreeView1.GetNodeAt(e.X, e.Y);

 

        // Was the node clicked on?

        if (! (nodeClicked == null))

            Console.WriteLine ("Node is: " + nodeClicked.Text);

        else

            Console.WriteLine("No node clicked.");

 

        // By default, right-clicking on a node does not set focus to

        // that node. This is especially important when you want to

        // use a ContextMenu control and associate it with a TreeView. 

        // This code shows how to do it.

        if (e.Button == MouseButtons.Right)

            this.TreeView1.SelectedNode = nodeClicked;

    }

 

Return to the tips page