How do I dynamically get name of a variable?

workfloat

New member
Joined
Jan 19, 2003
Messages
3
I am receiving a click event for a MenuItem in a Windows Forms app, but Im using a generic handler for all MenuItem clicks and I need to dynamically determine the name of the particular MenuItem in question because I am using part of the name to embed metadata describing what the MenuItem is supposed to do.

Is there a way to do obtain a variables name using reflection?

I suppose I could subclass MenuItem and add a field to store the information Im trying to extract, but if I can avoid that I would like to.
 
I would really recommend just creating a subclass of MenuItem by
inheriting it. Its really not hard at all, and its the best way. I had
the same problem as you, and thats what I ended up doing. Made
my life much easier.
 
Ok, I guess its probably less code than parsing the pertinent data from the variable name.

Since youve done this, are there any special considerations when using your subclassed MenuItems with ContextMenu, or does everything pretty much work as is?

Thanks for the very quick weekend feedback..
 
The Sender object passed in the event handler can be casted to
a MenuItem class, and then you can get that MenuItems name.

Code:
 In the event handler:
Dim mi As MenuItem = DirectCast(sender, MenuItem)
 
The Sender object passed in the event handler can be casted to

Its the getting of the name I dont get. Is there a name property on Windows Form objects? I didnt see one in the class hierarchy.

But even stil, I think I like VolteFaces suggestion better since I dont have to worry about parsing the name for the pertinent meta data, and I can just read from a custom property of my derived MenuItem class.

The only question left is are there any considerations when adding my custom MenuItems to .NETs ContextMenu and Menu classes, or will everything just work as is, since its a subclass with only one field added?
 
Since its a subclass, it will be compatible wherever a MenuItem is
compatible.
 
Menuitems dont have names. The (Name) property is added by an invisible Extender Provider which is only present at design time.
 
Back
Top