How do I dynamically get name of a variable?

workfloat

Newcomer
Joined
Jan 19, 2003
Messages
3
I am receiving a click event for a MenuItem in a Windows Forms app, but I'm 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 variable's name using reflection?

I suppose I could subclass MenuItem and add a field to store the information I'm 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. It's really not hard at all, and it's the best way. I had
the same problem as you, and that's 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 you've 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 MenuItem's name.

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

It's the getting of the name I don't get. Is there a name property on Windows Form objects? I didn't see one in the class hierarchy.

But even stil, I think I like VolteFace's suggestion better since I don't 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 .NET's ContextMenu and Menu classes, or will everything just work as is, since its a subclass with only one field added?
 
Menuitems don't have names. The (Name) property is added by an invisible Extender Provider which is only present at design time.
 
Back
Top