[Gtk-sharp-list] How to reference an object, given it's name?

Jonathan Pryor jonpryor@vt.edu
Thu, 28 Oct 2004 06:28:12 -0400


On Thu, 2004-10-28 at 00:10, Peter K. Gale wrote:
> Say you have an array of button objects named buttonA, buttonB, etc, and a
> corresponding array of event objects named eventA, eventB, etc. I am
> trying to find a clean way to link buttonX.Clicked with an action on
> eventX.
> 
> When a button is clicked, the handler will be passed a reference to that
> button object. Extracting the name of the button and changing the string
> from "buttonX" to "eventX" is easy. I am having problems trying to use the
> string "eventX" to reference the event object of the same name. Any ideas?
> If the process is as clean as I hope it is, it's probably one line of code.

I assume that the number of buttons and events is the same.  If this is
the case, you need do only two things: (1) ensure that the order of
buttons matches the order of events, e.g.

	Button[] buttons = {buttonA, buttonB, buttonC};
	Event[] events = {eventA, eventB, eventC};

(2) Use IList.IndexOf to find the index of the button, then index the
event array with the same index:

	IList b = buttons;
	int index = b.IndexOf (myButton);
	Event e = events[index];

If the number of buttons and events is *not* equal, then you'll have to
develop some mapping mechanism between buttons and events, possibly via
a Hashtable.

 - Jon