Will

Will

  • NA
  • 8
  • 0

Creating an unknown number of MenuItems, with an EventHandler that can determine which MenuItem was clicked

Feb 19 2007 1:48 PM
Hi;
Basically my problem is that I am polling a RS-485 highway for connected devices, and wish to display these names in a Menu at run time - I wish to be able to click on one of the devices in the Menu, and connect to it. I know that I need a .Click+= delegate for each of these items.
The issue that I am having is that I cannot tell which device is being clicked on!
When I created the items in my program, I iterated through the array of MenuItems, setting them to call the same delegate (passing a different parameter each time). I created my own function and delegate, which accepts an int (hidden in an EventArgs derived class); that is what I set as I stepped through the array - i.e. MyMenuItems[i].Click += new delegate { MyClickFunction(Object Sender, new MyEventArgs(i)); };
For whatever reason (I stepped through the program to find this out), the program sets up all the event handlers as it should have. However, when I click on one of the items in the list, the event handler always thinks the click came from the last item in the list - for a very interesting reason. I found that the program actually re-evaluates what the event handler should be... and so it always thinks that it came from the last item! Very strange.
I know it was set up correctly at the beginning of the program because I watched the variable, but it changed as soon as I clicked on the item.

I don't know if what I want to do is possible, I hope I have explained myself well enough... I had a hard time getting this to compile. My first try, I tried to create an actual event handler, but .Click would not let me add the event delegate to the list, since it was of the wrong type - I had to make the event handler with the EventHandler<MyEventArgs> , but .Click only accepts EventHandler without arguments.

Is there any way to set up an unknown (between 0 and 99) number of items to a menu, that will call a single function, passing a parameter to let me know which item was clicked.
In fact, any way to know what menu item was clicked would be great (remember I do not know ahead of time what these items would be called, or how many there are).
Any advice would be appreciated.
Thanks.

P.S. First Post!!

Answers (1)