I'm a fan of using dynamically created controls in my Dotnetnuke modules. It gives me the ability to build up helper routines that simplify the development of what I call summary, add/edit, view and search pages.
Over the past few months I've discovered a few helpful hints & tricks that might help the unaware so I've decided to publish them here.
Firstly what do I mean by dynamically generated controls?
Let's take a humble textbox, you can either drag from the toolbox, drop on the design surface then set the properties... or... create the control dynamically: (btw all my examples are in csharp)
TextBox tbx = new TextBox(); // create new text box
//set properties
tbx.CssClass = "myTBXstyle";
So what's the big deal I hear you say? Isn't it a pain to set property values all the time?
Simple, when you do it this way you can have these in some common code and it ensures you get consistency without having to set every property through the design interface everytime.
One of the first things to remember is that your dynamically created control needs to have an acceptable parent. For example a tablecell:
TableCell tc = new TableCell();
tc.Controls.Add(tbx);
The next thing is during postback, the LoadViewState handler normally rebuilds the controls from the asxc file so that posted form values can be inserted into those controls. With dynamically created controls this isn't going to happen automatically so you need to make it happen. Sounds complicated but is really quite simple.
Here's what works for me:
protected void Page_Load(object sender, EventArgs e)
{
if (!this.IsPostBack)
{
BuildForm();
}
}
private void BuildForm()
{
// build form logic goes here
saveViewState();
}
private void saveViewState()
{
ViewState["temp"] = new object();
base.SaveViewState();
}
protected override void LoadViewState(object savedState)
{
base.LoadViewState(savedState);
if (this.isPostBack)
{
BuildForm();
}
}
Next how to dynamically create Dotnetnuke controls such as the texteditor or labelcontrol.
DotNetNuke.UI.UserControls.TextEditor te = (TextEditor) Page.LoadControl("/controls/texteditor.ascx");
There is a gotcha with some of these controls, they must be connected to there parent controls collection before some of the properties can be accessed.
Hope this might help someone out there.