Using Dynamic Controls in DotNetNuke Module developemnt

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.

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值