Summary of dynamically adding controls on ASP.net pages

Source: Internet
Author: User
asp.net| Dynamic | control | page

The beginning of the way:

protected void Page_Load (object sender, EventArgs e)
{
if (! IsPostBack)
{
String ctr = "<asp:textbox runat= ' server ' id= ' haha ' text= ' button '/> ';
Control Ctrl = Page.parsecontrol (CTR);
PLACEHOLDER1.CONTROLS.ADD (ctrl);
}
}

The add control succeeds, but when the client is postback, the above text will cause the newly added control to disappear. Of course, if you remove the IsPostBack control, it will not disappear, but adding controls every time the client postbacks can cause unnecessary resource wastage. How to solve it?

You need to look at the life cycle of the page. Here just talk about what we need, do not need to see for yourselves (Recommended book bar "asp.net2.0 Technology Insider", sister article "asp.net2.0 Advanced Programming")

Preinit-->init-initcomplete->load .....

PreInit occurs at the beginning of page initialization.
Init occurs when a server control initializes, and initialization is the first step in the lifetime of the control.
InitComplete occurs when the page initialization completes.
Load occurs when the server control is loaded into the Page object.

Okay, we can go on with our action.
protected void Page_Init (Object Sernder, EventArgs e)
{
String ctr = "<asp:textbox runat= ' server ' id= ' haha ' text= ' button '/> ';
Control Ctrl = Page.parsecontrol (CTR);
PLACEHOLDER1.CONTROLS.ADD (ctrl);
}

Ok.

Test it yourself.



Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.