Dot Net Capsules

A Capsule on .NET, everyday, keeps you .NetHealthy!!!!

My Photo
Name:

Programmer. Visit my new blog at www.ashishsheth.com

Tuesday, April 26, 2005

Creating Controls Dynamically using Reflection

I have published this code months back at Developerdex. Republishing here.
The following method can be used in WinForms to create a control dynamically and put it on a
Windows forms.

Just the pass a fully quolified name of the control, for example "System.Windows.Forms.TextBox" and the function will do the rest, ie it will create the control, set the basic properties and place the control in a panel, here pnlDynControl.

For this method to work I have assumed that the assembly in which the control is defined is loaded into the memory and it is referenced by "myAssem" global variable(not necessary, u can change it). and the Control is derived from "System.Windows.Forms.Control" Class.

So here is the function:

private void CreateControl(string controlType)

{

System.Windows.Forms.Control ctrlDyn ;

Type t = myAssem.GetType(controlType) ;

System.Reflection.ConstructorInfo[] ctorInfo = t.GetConstructors() ;

pnlDynControl.Controls.Clear() ;

if(ctorInfo.Length >=0)

{

ctrlDyn = (System.Windows.Forms.Control)ctorInfo[0].Invoke(null) ;

ctrlDyn.Location = new Point(20,80) ;

ctrlDyn.Visible = true ;

ctrlDyn.Text = "Hi all" ;

ctrlDyn.Width = 100 ;

ctrlDyn.Height = 50 ;

pnlDynControl.Controls.Add(ctrlDyn) ;

}

}

0 Comments:

Post a Comment

<< Home

You Visitor Number:
Free Web Site Counter
Free Counter
free counters