Jump to content
Xtreme .Net Talk

Recommended Posts

Posted

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.

  • *Experts*
Posted

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.

Posted

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..

  • *Experts*
Posted

The Sender object passed in the event handler can be casted to

a MenuItem class, and then you can get that MenuItem's name.

 

' In the event handler:
Dim mi As MenuItem = DirectCast(sender, MenuItem)

"Being grown up isn't half as fun as growing up

These are the best days of our lives"

-The Ataris, In This Diary

Posted

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?

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Paste as plain text instead

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • Create New...