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.

1

2 Answers 2

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
}
Sign up to request clarification or add additional context in comments.

Comments

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

2 Comments

+1. I personally love to use the ItemClicked event, especially when each item's code is quite short (~5 lines). That way, I handle several items in one subroutine.
Yes, the ItemClicked is really helpful, especially when menu items share some common UI logic.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.