I have a method set to the click event handler in several Buttons and ToolStripMenuItems.
I want to get the Tag property of the sender to see which was clicked, but seems like ToolStripMenuItems can't be casted to Control.
How can I get the Tag property of both Buttons and ToolStripMenuItems?
Here's a simplified version of my method.
private void menu_Click(object sender, EventArgs e)
{
switch (((Control)sender).Tag.ToString())
{
case "X":
// do something
break;
case "Y":
开发者_如何学Go //do something else
break;
default:
//something else
break;
}
}
Thanks!
Because there's no common base class or interface of Button and ToolStripMenuItem that defines Tag, you will need to do a cast:
internal static object GetTag(object sender)
{
Button button = sender as Button;
ToolStripItem tsi = sender as ToolStripItem;
if (button != null)
return button.Tag;
if (tsi != null)
return tsi.Tag;
throw new ArgumentException("Unexpected sender");
}
精彩评论