C# Windows Forms - MenuItem Click Event - getting the MenuItem Text
How do I get the text of any given menu item that has been clicked on?
The menu is populated dynamically, so it seems I am limited to this:
Menu.MenuItems.Add(new MenuItem("MenuName", new EventHandler(menu_click)));
Unfortunately, I cannot see that Eventhandler has the text/name of 开发者_Python百科the menu item that has been clicked.
Is there a way around this?
What type of menu is this?
Since you seem to be attaching the event directly to the menu item then I would guess that sender is what you are looking for...
private void menu_click(object sender, EventArgs e)
{
MenuItem mi = sender as MenuItem;
// Access the clicked item here..
string text = mi.Text; // I guess it's called text(?)
}
Your event handler will have been given the object that raised the event as the "sender" parameter. You'll have to cast it to a MenuItem, then examine its "Text" property:
public void MenuClickHandler(object sender, EventArgs e)
{
var menuItem = (MenuItem)sender;
var menuText = menuItem.Text;
}
The event handler should have an object sender
parameter. If you cast this to a MenuItem
, you should be able to access the Header
property.
void menu_click (object sender, EventArgs e)
{
var clickedItem = sender as MenuItem;
if (clickedItem == null)
return;
if (clickedItem.HasHeader)
{
var text = clickedItem.Header;
}
}
With the standard .NET event handler function signature ...
(sender as Object, e as EventArgs) ' VB.NET syntax
... in the event handler, you can cast sender
as MenuItem
and access all of the properties.
You can cast the sender object to a menu item and retrieve the Text property.
Sample code
Menu.MenuItems.Add(new MenuItem("MenuName", (o, ev) =>
{
MessageBox.Show((o as MenuItem).Text);
}));
精彩评论