How to dail with controls at runtime?
-
I have made my own control inherited from System.Windows.Forms.UserControl then by using reflection I have created an object from my own control at run time after creation this control have been added to the collection of the container(form) System.Windows.Forms.Form.Controls. the problem is When the control is in the form (before runtime) it's easy to handel any of its events but now how to handel this control's events as (MouseDown , MouseUp , DragDrop , DragEnter and DragOver) as this control has never been created yet ?
-
I have made my own control inherited from System.Windows.Forms.UserControl then by using reflection I have created an object from my own control at run time after creation this control have been added to the collection of the container(form) System.Windows.Forms.Form.Controls. the problem is When the control is in the form (before runtime) it's easy to handel any of its events but now how to handel this control's events as (MouseDown , MouseUp , DragDrop , DragEnter and DragOver) as this control has never been created yet ?
So, somewhere in your code you have something like this:
YourControl control = Activator.CreateInstance(...);
this.Controls.Add(control);You have to associate the events after creating the object, before the control variable goes out of scope:
YourControl control = Activator.CreateInstance(...);
this.Controls.Add(control);control.MouseDown += ... ;
control.MouseUp += ... ;After writing += press tab and visual studio completes it for you. However if the you are trying to do something internal to the YourControl class, you should encapsulate the behavior in the class, associating the events in the constructor. Cheers,
rotter
-
I have made my own control inherited from System.Windows.Forms.UserControl then by using reflection I have created an object from my own control at run time after creation this control have been added to the collection of the container(form) System.Windows.Forms.Form.Controls. the problem is When the control is in the form (before runtime) it's easy to handel any of its events but now how to handel this control's events as (MouseDown , MouseUp , DragDrop , DragEnter and DragOver) as this control has never been created yet ?
Write the event handler beforehand, so you have something like this in your code:
public void ControlEventHandler(object sender, EventArgs args)
{
}and repeat this also for the mouse/drag event handlers. Next, when you create your control at runtime, simply assign these event handlers, like that:
Control ctl = new Button(); // some dynamic happening here
ctl.Click += new EventHandler(ControlEventHandler);
this.Controls.Add(ctl); // add this control at runtime to our controlregards