Techie Talks

Thursday, September 15, 2005

ASP.NET Dynamic control loading, placement and styling

In order to load a system control such as TextBox, use:
TextBox tx = new TextBox();
Controls.Add(tx);


This fails for some controls such as CheckBox. In such cases, add a panel, say "TestPanel" and add the control to the testpanel.

CheckBox cb = new CheckBox();
TestPanel.Controls.Add(cb);


In order to load a user control say MyUserControl.ascx, use
MyUserControl mucl = LoadControl("MyUserControl.ascx") as MyUserControl;
TestPanel.Controls.Add(mucl);


This way, the properties and methods exposed by MyUserControl can be accessed. However, the individual child controls cannot be accessed directly. They may have to be set as property values by the control's code behind.

Placing and editing style of the control
Once a control is created, before loading it to a the page (or panel), their position, style etc can be set using the control object's Style attribute using:

CheckBox cb = new CheckBox();
cb.Style["display"] = "block"; // The block style of display positions the control on a new block/line
TestPanel.Controls.Add(cb);

0 Comments:

Post a Comment

<< Home