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

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


In test.aspx.cs
protected void Page_Load(object sender, EventArgs e)
Button btn = new Button();
btn.ID = "btnSave";


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.

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);

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

Control's Lify cycle:

2.Load view state
3.Process postback data
5.Send postback change notifications
6.Handle postback events
8.Save state

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();

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

Original info:


Anonymous said…
thanks for sharing this. ;)
Ahsan Murshed said…
thanks for your comments

Popular posts from this blog

How can I get a value of a property from an anonymous type (C#)

The model backing the 'MyDBContext' context has changed since the database was created. Either manually delete/update the database, or call Database.SetInitializer with an IDatabaseInitializer instance. For example, the DropCreateDatabaseIfModelChanges strategy will automatically delete and recreate the database, and optionally seed it with new data.

"This request has been blocked because sensitive information could be disclosed to third party web sites when this is used in a GET request. To allow GET requests, set JsonRequestBehavior to AllowGet."