0

Another question from a C# newbie- I would like to use a single function to respond to a list of choices offered in the menu. When I run in debug mode I can hover the mouse over sender and it is clear that sender has the information I need, both the index of the item in the menu and the text associated with it. However, I have not figured out how to write code in a way that I get what I am looking for. The following does not compile:

int device;
private void myMenuItemInputClick(object sender, EventArgs e)
{
    device = sender.Index;
}

What I see when I put a breakpoint on myMenuItemInputClick and put the mouse over sender is:

sender {Windows.System.Forms.MenuItem, Items.Count:0, Text:Stereo Mix (Realtek High Defini}

Moving the mouse over the "+" sign so it becomes a "-" and a list of debug statements drops down shows that there is an item Index that is exactly what I want. How do I write the code that will get the item I'm looking for?

Uwe Keim
  • 39,551
  • 56
  • 175
  • 291
TomJeffries
  • 558
  • 1
  • 8
  • 25

2 Answers2

2

Cast the sender to MenuItem will possibly solve this problem.

int device;
private void myMenuItemInputClick(object sender, EventArgs e)
{
    device = ((MenuItem)sender).Index;
}

The variation Bharath mentioned would be something like,

int device;
private void myMenuItemInputClick(object sender, EventArgs e)
{
    var menuItem = sender as MenuItem;
    if(menuItem != null)
        device = menuItem.Index;
}
Andy
  • 366
  • 1
  • 4
  • Perfect. That did it. Casts in C# operate in ways I don't completely understand yet. – TomJeffries Sep 04 '13 at 05:10
  • No worries. Most event objects can be cast the same way. – Andy Sep 04 '13 at 05:13
  • Explicit type casting like `(MenuItem)sender` might throw exception. Better use `is` or `as` when conversion and check for null. – Carbine Sep 04 '13 at 05:13
  • [Reference](http://stackoverflow.com/questions/2483/casting-newtype-vs-object-as-newtype?lq=1) for `is` or `as` type cast – Carbine Sep 04 '13 at 05:19
0

Try casting the sender object to the type you are working on. You should be able to fetch the properties.

E.g.

var menuItem= sender as MenuItem;
menuItem.Index
Carbine
  • 7,849
  • 4
  • 30
  • 54