Wednesday, March 23, 2005

Dynamic User Controls in ASP.Net pages

Creating Dynamic user controls and adding them to asp.net pages can be tricky. I searched for a while on google, and found tons of helpful articles about how to add dynamic controls to a page. All of the articles basically said the same thing:
  1. Create the control in code
  2. Add the control to the page's Controls collection
  3. Set properties on the control


Here's an example:

private void Page_Load(object, System.EventArgs )
{
    CheckBox cb = new CheckBox();
    Page.Controls.Add( cb );

    cb.Checked = true;
}

This will ensure that your control is visible on the page, and the control's viewstate will be saved across requests.

The simple method breaks down when adding User Controls, though.

If you want to add a user control, and be able to access it's child controls(why wouldn't you?), you have to follow the same steps, but instantiating the control is different.

private void Page_Load( object, System.EventArgs)
{
    MyControl mc = LoadControl( "MyControl.ascx" );
    Page.Controls.Add( mc );

    mc.Controls[0].Text = "Hello";
}


Note that you have to call LoadControl( string Path ) to get your control loaded, else all of the child controls that are owned by your user control will be null.

Man that was hard to find. Here's the original article where I found the info:
http://aspalliance.com/565.

No comments: