Question

I have a ContextMenuStrip That I create in code:

ContextMenuStrip menu;
public Loader()
{
    menu = new ContextMenuStrip();
    menu.Items.Add("Set Complete");
    menu.Items.Add("Set Review");
    menu.Items.Add("Set Missing");
}

I need to add code that will run when a certain Item is clicked. So far I have tried this:

if (menu.Items[0].Selected)
{
    //code
}

if (menu.Items[1].Selected)
{
    //code
}

if (menu.Items[2].Selected)
{
   //code
}

But (suprise, suprise) It doesnt work.

I think I might need to set up an event handler for each Item, but am unsure how to do this as I created the ContextMenuStrip with code.

Was it helpful?

Solution

You have to subscribe the click events. I have changed your sample so it should work:

public Loader()
{
    var menu = new ContextMenuStrip();
    var menuItem = menu.Items.Add("Set Complete");
    menuItem.Click += OnMenuItemSetCompleteClick;
    menuItem = menu.Items.Add("Set Review");
    menuItem.Click += OnMenuItemSetReviewClick;
    menuItem = menu.Items.Add("Set Missing");
    menuItem.Click += OnMenuItemSetMissingClick;
}

private void OnMenuItemSetCompleteClick(object sender, EventArgs e)
{
    // Do something
}

private void OnMenuItemSetReviewClick(object sender, EventArgs e)
{
    // Do something
}

private void OnMenuItemSetMissingClick(object sender, EventArgs e)
{
    // Do something
}

OTHER TIPS

You should add event handlers to the individual menu items (Click event), or to the ContextMenuStrip itself (ItemClicked event).

Take a look here: How to respond to a ContextMenuStrip item click

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top