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:
Post a Comment