- Create the control in code
- Add the control to the page's Controls collection
- 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:
Post a Comment