0

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.

pravprab
  • 2,301
  • 3
  • 26
  • 43
maffo
  • 1,393
  • 4
  • 18
  • 35
  • possible duplicate of [How to make a contextMenuStrip item click event](http://stackoverflow.com/questions/5789023/how-to-make-a-contextmenustrip-item-click-event) – João Angelo Dec 15 '11 at 12:21

2 Answers2

2

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

Community
  • 1
  • 1
Anders Marzi Tornblad
  • 18,896
  • 9
  • 51
  • 66
2

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
}
Fischermaen
  • 12,238
  • 2
  • 39
  • 56