Link to home
Start Free TrialLog in
Avatar of newstandard
newstandard

asked on

TreeView context menu

I have a treeview control on a form.  I want the user to be able to right-click on a node and select different options from a context menu, such as "Delete", "Add Child", etc.  I have this functionality working by having the TreeView's ContextMenu property set to the context menu.  When those menu items fire, I use the MyTreeView.SelectedNode property to access the proper node to take action upon.

There is a bug, however.  If you right click on a node, it will turn blue as if it is the selected member of the TreeView.  However, when the menu items fire, the SelectedNode property is still equal to the previously selected node (even though it is not blue).  Then, after the menu fires, the previously selected node turns blue again.  So the node you right-clicked on was never actually selected.  This means that the user, to get proper results, has to left-click on a node, and then right-click on it to get the menu.

I want a right-click to select the node first, and then bring up the context menu.  What is the easiest way to do that?

Thanks,

Justin
Avatar of PhilipRocks
PhilipRocks

You could select it programmatically before showing the context menu:

private void treeView1_MouseUp(object sender, System.Windows.Forms.MouseEventArgs e)
{
if( e.Button == MouseButtons.Right)
                  {
                        treeView1.SelectedNode = treeView1.GetNodeAt( e.X, e.Y);
                  }
            }
ASKER CERTIFIED SOLUTION
Avatar of PhilipRocks
PhilipRocks

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
SOLUTION
Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Avatar of newstandard

ASKER

Thanks!  I added this code to my form:

private void myTree_MouseDown(object sender, System.Windows.Forms.MouseEventArgs e)
{
      if (e.Button == MouseButtons.Right)
      {
            Point p = new Point(e.X,e.Y);
            TreeNode nodeUnderMouse = myTree.GetNodeAt(p);
            if (nodeUnderMouse != null)
            {
                  myTree.SelectedNode = nodeUnderMouse;
            }
      }
}

Everything is working fine now.