Associate custom data with MenuItem

  • Thread starter Aliaksandr Radzivanovich
  • Start date
A

Aliaksandr Radzivanovich

Is there any way to associate some variable with a MenuItem object?
Most of the controls in Windows Forms have Tag property that holds anything
that you assing to it. It is very useful, but unfortunately MenuItem doesn't
have this property. The only customizable item is Text property, which is
not enough to me.
I my projet I create a menu, populate its items dynamically (using list of
files in a folder, for exapmle), attach one event handler to all the items.
How to make the event handler to receive some identifier from a clicked menu
item?
I want to show meaningful user-friendly text in menu items, that's why I
can't use Text property as a parameter for my event handler, after all,
there may be duplicates in names I want to show in menu items.
Does anybody know how to help me?
Thanks.
 
J

Joe White

Try creating a Hashtable, and storing your data in there, using the
MenuItem instance as the key.

Hashtable menuData = new Hashtable();
menuData[menuItem1] = "file1.txt";
menuData[menuItem2] = "file2.doc";
 
B

Bob Powell [MVP]

Is there any way to associate some variable with a MenuItem object?

You can create an Extender Provider class to associate any data with a menu
item. Instead of handling the MenuItem Click method directly, have the
extender provider handle the click and then you subscribe to an event in the
extender-provider which can inform your code of the click and provide a
custom event argument containing the custom data.

Last month's issue of Well Formed had an article on creating
extender-providers for menu-items that could easily be adapted to your
requirements. Check out that issue here
http://www.bobpowell.net/August2003.htm

--
Bob Powell [MVP]
C#, System.Drawing

September's edition of Well Formed is now available.
http://www.bobpowell.net/currentissue.htm

Answer those GDI+ questions with the GDI+ FAQ
http://www.bobpowell.net/gdiplus_faq.htm
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top