In Windows Forms, you can only add strings to be displayed in a menu. It would be a lot easier if you could add entire objects to a MenuItem, which could override their ToString()-method to determine the way to represent them in the menu item. For instance, you may want to map menu items to objects so that when the menu item is clicked, you immediately get the correct object in the event handler's sender object. Now, there is no way to associate an object with a menu item.
As a solution, you could consider subclassing the MenuItem class and adding a Tag property that can contain any Object. It is impossible to override the Text property of the MenuItem class so you must set the Text property to the tag object's ToString() value at construction or when the Tag property changes. Now when you listen for the Click event of the MenuItem, cast the sender to your MenuItem subclass and obtain the associated object through the Tag property.
Code sample for a generic MenuItem class with a Tag property:
public class TaggedMenuItem : System.Windows.Forms.MenuItem
{
private object _tag;
public object Tag
{
get { return _tag; }
}
public TaggedMenuItem( object tag )
{
_tag = tag;
if( tag != null ) this.Text = tag.ToString();
}
}
Of course you can do a whole lot more with this kind of subclassing but this can serve as an easy start...