开发者

How can i fix the issue for context menu for Treeview click

开发者 https://www.devze.com 2023-01-28 04:23 出处:网络
My code for opening a context menu on Right-click for a treeview is as follows private void contextMenu_Opening(object sender, CancelEventArgs e)

My code for opening a context menu on Right-click for a treeview is as follows

private void contextMenu_Opening(object sender, CancelEventArgs e)
    {
        if (Convert.ToInt16(tvwACH.SelectedNode.Tag) == 1)
        {
            contextMenu.Items.Add(New);
            contextMenu.Items.Remove(Remove);
            contextMenu.Items.Remove(Saveas);
            contextMenu.Items.Remove(Save);
            conte开发者_StackOverflowxtMenu.Items.Remove(addEntry);
        }
        if (Convert.ToInt16(tvwACH.SelectedNode.Tag) == 2)
        {
            contextMenu.Items.Add(New);
            contextMenu.Items.Remove(Remove);
            contextMenu.Items.Remove(Saveas);
            contextMenu.Items.Remove(Save);
            contextMenu.Items.Remove(addEntry);
            New.Text = "Add FileHeader";
        }
        if (Convert.ToInt16(tvwACH.SelectedNode.Tag) == 3)
        {
            contextMenu.Items.Remove(New);
            contextMenu.Items.Add(Save);
            contextMenu.Items.Add(Saveas);
            contextMenu.Items.Remove(Remove); //Added later
            contextMenu.Items.Remove(addEntry);
        }
        if (tvwACH.SelectedNode.Parent != null)
        {
            string str = tvwACH.SelectedNode.Parent.ToString().Substring(10);
            if (str == "BatchHeader")
            {
                contextMenu.Items.Remove(New);
                contextMenu.Items.Remove(Save);
                contextMenu.Items.Remove(Remove);
                contextMenu.Items.Remove(Saveas);
                contextMenu.Items.Add(addEntry);
            }
        }

and also mouse down for treeview as follows

 private void tvwACH_MouseDown(object sender, MouseEventArgs e)
    {
        if (e.Button == MouseButtons.Right)
        {
            contextMenu.Show(tvwACH, e.Location);
        }
        location = e.Location;
    }

But this getting opened every where on tree-view control but i only need it to be opened when i click on Nodes of my tree-view.

Any help please


If you only want the context menu to be displayed when the user right-clicks on a node, you need to include some logic in your MouseDown event hander to verify that the click event occurred over a node.

You can determine the node that is located at a particular point using the HitTest method provided by the TreeView. For example, you could modify your current MouseDown event handler to include the following code:

private void tvwACH_MouseDown(object sender, MouseEventArgs e)
{
    if (e.Button == MouseButtons.Right)
    {
        if (tvwACH.HitTest(e.Location).Node != null)
        {
            contextMenu.Show(tvwACH, e.Location);
        }
    }
}
0

精彩评论

暂无评论...
验证码 换一张
取 消