开发者

Get Tag property from ToolStripMenuItem and Button in click event handler

开发者 https://www.devze.com 2023-02-09 16:36 出处:网络
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 likeToolStripMenuItems can\'

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");
}
0

精彩评论

暂无评论...
验证码 换一张
取 消