David Torrey
David Torrey

Reputation: 1342

C# ContextMenu EventArgs

when building a click event method for a context menu, what does the Event Args pass on a click event?

I'm trying to build a context menu for a Tree-list so that when i right click on a folder i have the option to create a new folder. What I'm trying to figure out is how to pass the folder that was clicked on so that i can create the folder in the correct location.

this is what I have so far:

    private void qList_NodeMouseClick(object sender, TreeNodeMouseClickEventArgs e)
    {
        if(e.Button == System.Windows.Forms.MouseButtons.Right)
        {
            ContextMenu cm = new ContextMenu();

            //folder or file
            if(e.Node.ImageKey == "folder")
            {
                cm.MenuItems.Add(new MenuItem("Create New Folder",CreateNewFolder_Click));
                cm.MenuItems.Add("Create New QPack");
                cm.MenuItems.Add("Remove New Folder");
                e.Node.ContextMenu = cm;
            }
            else if (e.Node.ImageKey == "files")
            {
                cm.MenuItems.Add("Create QPack", CreateNewQPack_Click);
                cm.MenuItems.Add("Remove QPack");
                e.Node.ContextMenu = cm; 
            }

        }
    }

    private void CreateNewFolder_Click(object sender, EventArgs e)
    {

    }

    private void CreateNewQPack_Click(object sender, EventArgs e)
    {

    }

Upvotes: 0

Views: 3407

Answers (2)

elpaulo
elpaulo

Reputation: 96

Another way to do it is to create your own custom MenuItem like this :

public class CustomMenuItem : MenuItem
{
    public TreeNode SelectedTreeNode { get; set; }

    public CustomMenuItem(string text, EventHandler onClick, TreeNode treeNode) : base(text, onClick)
    {
        SelectedTreeNode = treeNode;
    }
}

So instead of creating your menuitem like you do here :

cm.MenuItems.Add(new MenuItem("Create New Folder",CreateNewFolder_Click));

Yo do :

cm.MenuItems.Add(new CustomMenuItem("Create New Folder", CreateNewFolder_Click, e.Node));

Then you will get your TreeNode in your method like this :

private void CreateNewFolder_Click(object sender, EventArgs e)
{
    CustomMenuItem customMenuItem = sender as CustomMenuItem;
    MessageBox.Show(customMenuItem.SelectedTreeNode.FullPath);
}

Upvotes: 1

vgru
vgru

Reputation: 51224

You can simply create an anonymous event handler which will capture any relevant data and pass it to a different method:

var menuItem = new MenuItem(
    "Create New Folder",
    // the following lambda will capture the `e` parameter
    (sender, args) => DoSomething(e.Node, "stuff just happened"));

Upvotes: 3

Related Questions