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 ]