Friday 22 August 2008

How do I create controls at runtime in ASP.NET

If you want to create controls at runtime and render them, the LoadControl method should be used instead of doing a normal object declaration. This is the only way that child controls (within the control you want to create) will be instantiated. The LoadControl method accepts the virtual path to the control as a string (e.g. *.ascx file) or the type of control and it's arguements as an object array (pass in null if no arguements need to be supplied). The second overload can be used if the control is part of a class library.

Although you're creating an object of the control type, I wouldn't recommend doing the following because null reference exceptions will be thrown when any child control is referenced:
MyControl myControl = new MyControl();

These examples show how dynamically create controls correctly:

Example 1:

MyControl myControl = LoadControl( "MyControl.ascx" ) as MyControl;

if ( myControl != null )
{
// Do something.
}

Example 2:

MyControl myControl = LoadControl( typeof( MyControl ), null ) as MyControl;

if ( myControl != null )
{
// Do something.
}

I normally have a PlaceHolder indicating the position where I want this dynamic content:

phDynamicControls.Controls.Add( myControl );

No comments: