How to determine which menu option was pressed?

P

PeterZ

Hoping one of you menu gurus can help out with this one....

I'm creating a sub menu programatically with X number of options.

The thing I'm stuck on is determining which menu option was pressed
within the menu event handler. Is there a way to pass the menu index
or menu text to the event handler?

-----------------------------------------
This is where I create the menu options:
-----------------------------------------

private void CreateSubMenu()
{
string sMenuText;

// Creates a sub menu with "Option 1", "Option 2", "Option 3",
etc...
for (int i=1; i <= giAvailableOps; i++)
{
sMenuText = "Option " + i.ToString();
MenuItem NewMenuItem = new MenuItem();
NewMenuItem.Text = sMenuText;
NewMenuItem.Click += new
System.EventHandler(this.mnuAddFeature_Click);
mnuAddFeature.MenuItems.Add(NewMenuItem);
}
}

---------------------------------------
My event handler for the menu options:
---------------------------------------

private void mnuAddFeature_Click(object sender, System.EventArgs e)
{
// I need to determine which menu option was pressed.
// The following code just returns "System.EventArgs"
MessageBox.Show(e.ToString());
}
 
K

kenan

hope this helps....

private void mnuAddFeature_Click(object sender,
System.EventArgs e)
{
int i = mnuAddFeature.MenuItems.IndexOf(sender);

MessageBox.Show(i.ToString());
}
 
D

Darkwing

I had this problem too but the other solutions would not
work for me since my menu is built dynamically and I
support several languages.
I suggest subclassing MenuItem and place a variable to
hold additional informaion in that value.
Then just.

((MyMenuItem)sender).FunctionID

James.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top