Display context menus for TreeView items in C#

[context menus]

This example displays different context menus when you right-click on different kinds of nodes in a TreeView control. In this example, different nodes represent factories, groups, or individuals. Different node types display different context menus.

When it starts, the program adds data to its TreeView control just as the example Display tooltips for TreeView nodes in C# does. When you press the right mouse button down over a node, the following MouseDown event handler executes.

// Display the appropriate context menu.
private void trvOrg_MouseDown(object sender, MouseEventArgs e)
{
    // Make sure this is the right button.
    if (e.Button != MouseButtons.Right) return;

    // Select this node.
    TreeNode node_here = trvOrg.GetNodeAt(e.X, e.Y);
    trvOrg.SelectedNode = node_here;

    // See if we got a node.
    if (node_here == null) return;

    // See what kind of object this is and
    // display the appropriate popup menu.
    if (node_here.Tag is FactoryData)
        ctxFactory.Show(trvOrg, new Point(e.X, e.Y));
    else if (node_here.Tag is GroupData)
        ctxGroup.Show(trvOrg, new Point(e.X, e.Y));
    else if (node_here.Tag is PersonData)
        ctxPerson.Show(trvOrg, new Point(e.X, e.Y));
}

If the mouse button is not the right button, the code does nothing. If this is the right button, the code uses the TreeView control’s GetNodeAt method to find the node under the mouse. It sets the TreeView control’s SelectedNode property to that node. If the node is null, the event handler then exits.

If the code gets this far (it’s the right mouse button and there is a node under the mouse), then the program examines the type of object contained in the node’s Tag property and displays the appropriate context menu. The parameters to the calls to the context menus’ Show method tell which control is associated with the menu and where the menu should be positioned.

The context menus all have a Delete command labeled appropriately: Delete Factory, Delete Group, or Delete Person.

The following code shows the code behind each of the context menus’ Delete commands.

private void mnuFactoryDelete_Click(object sender, EventArgs e)
{
    trvOrg.SelectedNode.Remove();
}

private void mnuGroupDelete_Click(object sender, EventArgs e)
{
    trvOrg.SelectedNode.Remove();
}

private void mnuPersonDelete_Click(object sender, EventArgs e)
{
    trvOrg.SelectedNode.Remove();
}

Each of the commands simply deletes the TreeView control’s selected node, which was set by the control’s MouseDown event handler.


Download Example   Follow me on Twitter   RSS feed   Donate




This entry was posted in controls, user interface and tagged , , , , , , , , , , . Bookmark the permalink.

Leave a Reply

Your email address will not be published. Required fields are marked *