IntroductionIn this snippet I will explain how to add controls dynamically in asp.net and register events for the controls and make it work events perfectly. Last week I have read the forums many readers asking about add controls dynamically in asp.net giving problems and also it not working properly with events. So I have decided write the snippet for you. ImplementationLet’s create a simple page with a PlaceHolder to add control from code behind. Html Code <%@ Page Language="C#" AutoEventWireup="true" CodeFile="SortElement.aspx.cs" Inherits="SortElement" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title>Dynamically Adding Controls in ASP.NET</title>
</head>
<body>
<form id="form1" runat="server">
<div>
<asp:PlaceHolder ID="plMain" runat="server"></asp:PlaceHolder>
</div>
</form>
</body>
</html>Now navigate to the code behind add a button control into PlaceHolder by code as like below, C# code using System;
using System.Data;
using System.Configuration;
using System.Collections;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
public partial class SortElement : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
Button btn = new Button();
btn.ID = btnSave;
btn.Click += new EventHandler(btn_Click);
this.plMain.Controls.Add(btn);
}
void btn_Click(object sender, EventArgs e)
{
Response.Write("<p>The Button has clicked</p>");
}
}Now button is added and when I click button make a post back, but unfortunately button was disappeared. The reason is when we are click button it make post back, so each post back there page load from top to bottom. There is easy solution for this issue. You have to select a correct event to place the code to add control into page dynamically. The best and correct event is Page_Init.
Init Event:http://msdn.microsoft.com/en-us/library/ms178472.aspx I have modified previous code as like below. C# Code using System;
using System.Data;
using System.Configuration;
using System.Collections;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
public partial class SortElement : System.Web.UI.Page
{
protected override void OnPreInit(EventArgs e)
{
Button btn = new Button();
btn.ID = btnSave;
btn.Click += new EventHandler(btn_Click);
this.plMain.Controls.Add(btn);
base.OnPreInit(e);
}
protected void Page_Load(object sender, EventArgs e)
{
// here only processing.
}
void btn_Click(object sender, EventArgs e)
{
Response.Write("<p>The Button has clicked</p>");
}
}Now run application and click button it was there and it will work fine.Hopes help. |