Wednesday, February 10, 2010

Dynamically add control in asp.net

Recently I have faced a problem when try to dynamically add controls in asp.net, like this,
In test.aspx page

<body>
    <form id="form1" runat="server">
    <div>
        <asp:PlaceHolder ID="PlaceHolder1" runat="server" >    </asp:PlaceHolder>

    </div>
    </form>
</body>

In test.aspx.cs
protected void Page_Load(object sender, EventArgs e)
{
Button btn = new Button();
btn.ID = "btnSave";
this.PlaceHolder1.Controls.Add(btn);
}

Problem:

It is working fine but when I press any button I mean any post back occur It disappears.
After search for a long time I got the proper solution, now I would like to share this with you.

Solution:
To avoid this problem one should dynamically load the controls during Page_Init because we may want to hook up our events with proper handler at an early stage.

protected void Page_Init(object sender, EventArgs e)
{
Button btn = new Button();
btn.ID = "btnSave";
btn.Click+=new EventHandler(btn_Click);
this.PlaceHolder1.Controls.Add(btn);
}

Some Tips:
In addition I have got more tips on it,

Control's Lify cycle:

1.Initialization
2.Load view state
3.Process postback data
4.Load
5.Send postback change notifications
6.Handle postback events
7.Prerender
8.Save state
9.Render
10.Dispose
11.Unload

You will get details from here:http://msdn.microsoft.com/en-us/library/aa719775%28VS.71%29.aspx

1.During Page_Init you cannot assign dynamic control property,because in Page_Init event Initialization happens before loadViewState in control's life cycle.The value assigned to the properties during Initialization will simply get overwritten by the ViewState values.

2.If you are expecting your ViewState to retain after the postback, always assign same ID to the dynamic control,if you use like this,

protected void Page_Init(object sender, EventArgs e)
{
TextBox t = new TextBox();
t.ID = Guid.NewGuid().ToString();
this.form1.Controls.Add(t);
}

It will not work. You should use same id or fixed id ,
like this, t.ID="txtName";


Original info:
http://geekswithblogs.net/shahed/archive/2008/06/26/123391.aspx

2 comments:

Anonymous said...

thanks for sharing this. ;)

Unknown said...

thanks for your comments

Method 'StartWorkflowOnListItem' in type 'Microsoft.SharePoint.WorkflowServices.FabricWorkflowInstanceProvider'

Exception: Method 'StartWorkflowOnListItem' in type 'Microsoft.SharePoint.WorkflowServices.FabricWorkflowInstanceProvider'...