"If at first you don't succeed; call it version 1.0" :-Unknown

Pages

Saturday, January 22, 2011

Dynamically Adding Controls in ASP.NET

In my previous post i show Dynamically adding controls on grid with validation. I know this an old topic 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.


Implementation

Let’s create a simple page with a PlaceHolder to add control from code behind.

Html Code


<html xmlns="http://www.w3.org/1999/xhtml">
<head id="Head1" 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>



C# Code




protected override void OnPreInit(EventArgs e)
    {
        Button btn = new Button();
        btn.ID = "btnSave";
        btn.Text = "Click Me";
        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 the reason why some programmers getting error because they try to create controls(Button) on pageload event. After the 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

Have a nice day... 'N happy Coding :)

No comments: