tags:

views:

364

answers:

4

I want to cast both MenuItem objects and Button control objects to an object type of whose "Tag" property I can reference.

Is there such an object type?

E.g.

void itemClick(object sender, EventArgs e)
{
    Control c = (Control)sender;
    MethodInvoker method = new MethodInvoker(c.Tag.ToString(), "Execute");
    method.Invoke();
}

Except this fails - "Unable to cast object type 'System.Windows.Forms.MenuItem' to type 'System.Windows.Forms.Control'

What can replace Control in this example?

A: 

Control is what you're looking for.

blue_fenix
Sorry my mistake. The example now contains control as this doesn't work either. I had previously tried this.
Stuart Helwig
+1  A: 

the inheritance path is different for MenuItem and Button, there is no shared / inherited Tag property.

MenuItem inherits from Menu Which declares a Tag property, Button Inherits from Control which also implements a Tag propery. You should be able to cast both MenuItem and Button to Component, but this won't help you as the Tag property is declared in the derived classes I mentioned (menu and control).

In this specific case you would probably need to use reflection rather than inheritance. Or come up with plan B

Tim Jarvis
+2  A: 

I am writing this without IDE.


object myControlOrMenu = sender as MenuItem ?? sender as Button;
if (myControlOrMenu == null)
// neither of button or menuitem

shahkalpesh
+2  A: 

Use "as" operator.

object tag;
Button button;
MenuItem menuItem = sender as MenuItem;
if (menuItem  != null)
{
 tag = menuItem.Tag;
}
else if( (button = sender as Button) != null )
{
 tag = button.Tag;
} else 
{
//not button nor MenuItem 
}
Michał Piaskowski
Perfect. Thanks.
Stuart Helwig