Click here to Skip to main content
15,897,273 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
hi
i am unabel to show the contexmenue strip i am using below code

ContextMenuStrip abc = new ContextMenuStrip();
if (e.Button == MouseButtons.Right)
{
treeView1.SelectedNode = e.Node;
abc.Show(treeView1, e.Location);
}
please help me out.
Posted

1 solution

A Win Form ContextMenuStrip is a "Component" meant to be associated with an entire Control, or multiple Controls.

If you set the ContextMenuStrip Property of the TreeView to use the ContextMenuStrip you've added to the Form at design-time, then it's going to appear whenever you context-click anywhere in the TreeView's DisplayRectangle bounds: that's independent of any Node, or Nodes, being Selected.

If you wish to limit the display of the ContextMenu, here's an example that will only show it on context-click when the TreeNode you context-click on happens to be the SelectedNode of the TreeView:
C#
// define at Form scope
private TreeNode currentRightClickedTreeNode;
private bool IsContextMenuHidden = false;

// handle the TreeView MouseDown
private void treeView1_MouseDown(object sender, MouseEventArgs e)
{
    IsContextMenuHidden = false;

    if (e.Button == MouseButtons.Right)
    {
        currentRightClickedTreeNode = treeView1.GetNodeAt(e.Location);
        IsContextMenuHidden = currentRightClickedTreeNode == null || currentRightClickedTreeNode != treeView1.SelectedNode;
    }
}

// handle the ContextMenu Opening Event
private void contextMenuStrip1_Opening(object sender, CancelEventArgs e)
{
    e.Cancel = IsContextMenuHidden;
}
This works by testing for two conditions that determine whether or not the ContextMenu is shown:

1. does the context-click occur somewhere "outside" all TreeNodes

2. does the context-click occur on a TreeNode that is not selected
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)

  Print Answers RSS
Top Experts
Last 24hrsThis month


CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900