ASP.Net Host

How to add an ASP.Net control at runtime

If you ever wanted to add a ASP.Net control to your web form at runtime, it is actually pretty easy. This sample will add a LinkButton to the form at runtime. You don't have to load it during the PageLoad event like I have, but you can add it at anytime and from any event in the page. 

So put this into your webform's html view:

<div>
    <asp:PlaceHolder ID="PlaceHolder1" runat="server"></asp:PlaceHolder>
    <asp:Literal ID="Literal1" runat="server"></asp:Literal>
</
div>

You need to put a PlaceHolder in your ASP.net page where you want the control to appear. You don't need the literal, but in this sample is used to show that the linkbutton we add will actually fire it's click event.

Here is the code-behind page that will add the LinkButton and wire its click event.

protected void Page_Load(object sender, EventArgs e)

    LoadLinkButton();
}
protected void LoadLinkButton()

    LinkButton LinkButton1 = new LinkButton(); 
    LinkButton1.Text = "Button Text"; 
    LinkButton1.Click += new EventHandler(LinkButton1_Click); 
    this.PlaceHolder1.Controls.Add(LinkButton1);
}
protected void LinkButton1_Click(object sender, EventArgs e)

    this.Literal1.Text = "Link was clicked.";
}


In the LoadLinkButton function, we create a new linkButton control, assign it's Text and its Click event, and then add it to the placeHolder so it will be visible on the web form.

You can do this with any ASP.net control so don't limit yourself to linkButtons.

Cheers,
Marc Talcott
ASP.Net Host

[ 3/16/2007 ]

0 Comments

Leave your comment.
Name:
Email: (not shared or made public)
Website:   http://
Comments:

This is a public forum. Aquest Solutions and its affiliates are not responsible for, and do not control what is posted herein. Aquest Solutions makes no warranties or guarantees concerning any advice dispensed by its staff, members, or readers.

Community standards in this comment area do not permit hate language, excessive profanity, or other patently offensive language. Please be aware that all information posted to this comment area becomes the property of Aquest Solutions and may be edited and republished in print or electronic format as outlined in Aquest Solutions' Terms of Use.

Important Note: This comment area is NOT intended for commercial messages or solicitations of business.

We recommend Aquest Hosting for your ASP.Net 2.0 hosting, Community Server hosting, and DotNetNuke hosting.