Dynamically instantiated custom control events...

  • Thread starter Thread starter Tim
  • Start date Start date
T

Tim

I have a custom control with it's own click event that does a few things
internally. In Form1, I loop thru a database query result set, and build x
number of these controls using:
CustControl ctl =
(CustControl)Activator.CreateInstance(typeof(CustControl));
// set properties...
ctl.Property = value;

I stuff each ctl into an ArrayList. A bit later, I loop thru that ArrayList
and place these controls on Form1.

I would like to be able to have the custom control's click event communicate
to Form1 using delegates/events so that a method on Form1 can receive some
data from that control and process it.

I've done something like this before using a custom control, but it was not
dynamically created. In this case I built a custom EventArgs class, declared
a delegate with it, and on Form1, simply handled the event like any other
designer control like:
this.customControl.BtnPrevClick += new
CustomControl.ButtonEventHandler(customControl_BtnPrevClick);
Since I can't do this with a dynamically created control, I'm posting for
help here.

Any help will be greatly appreciated,
Tim
 
You can do it dynamically with reflection, which is a little tiresome.

I would recommend creating a 'universal' event which is implemented in all
of your custom controls. That way you can always cast back to that interface
(eg 'MyCustomControl') and hook the event by name (rather than reflection).
The universal event parameters can contain the eventname and a parameter
array etc.

I have just recently faced the same problem. And this method worked well for
me.

Fletch.
 
Oops I should point out that i meant create a base class that
implements/defines the universal event and derive all custom controls off
that :)
 
Back
Top