How to add Control dynamically in an ASP.NET AJAX application

Most of us know how to create controls dynamically in an ASP.NET application. However a lot of users get confused while creating controls dynamically in an ASP.NET AJAX application. This is as the there is an async postback involved. Here's a very common technique to create controls dynamically in an ASP.NET AJAX application using ViewState


<body>


    <form id="form1" runat="server">


    <div>


    <asp:ScriptManager ID="ScriptManager1" runat="server">


    </asp:ScriptManager>


    <asp:UpdatePanel ID="UpdatePanel1" runat="server">


    <ContentTemplate>


           <asp:Button ID="Button1" runat="server" Text="Create TextBoxes" onclick="Button1_Click" />


   </ContentTemplate>


   </asp:UpdatePanel>


    </div>


    </form>


</body>




C#


    protected void Button1_Click(object sender, EventArgs e)


    {


        int cnt = 0;


 


        if (ViewState["txtBoxes"] != null)


            cnt = (int)ViewState["txtBoxes"];


 


        cnt = cnt + 1;


        ViewState["txtBoxes"] = cnt;


 


 


        for (int i = 0; i < cnt; i++)


        {


            TextBox tb = new TextBox();


            tb.Text = "";


            tb.ID = "TextBox" + cnt;


            UpdatePanel1.ContentTemplateContainer.Controls.Add(tb);


        }    


    }




VB.NET


    Protected Sub Button1_Click(ByVal sender As Object, ByVal e As EventArgs)


        Dim cnt As Integer = 0


 


        If ViewState("txtBoxes") IsNot Nothing Then


            cnt = CInt(Fix(ViewState("txtBoxes")))


        End If


 


        cnt = cnt + 1


        ViewState("txtBoxes") = cnt


 


 


        For i As Integer = 0 To cnt - 1


            Dim tb As New TextBox()


            tb.Text = ""


            tb.ID = "TextBox" & cnt


            UpdatePanel1.ContentTemplateContainer.Controls.Add(tb)


        Next i


    End Sub




Will you give this article a +1 ? Thanks in advance


About The Author

Suprotim Agarwal
Suprotim Agarwal, ASP.NET Architecture MVP (Microsoft Most Valuable Professional) works as an Architect Consultant and provides consultancy on how to design and develop Web applications.

Suprotim is also the founder and primary contributor to DevCurry, DotNetCurry and SQLServerCurry. He is the Editor of a Developer Magazine called DNC Magazine. He has also written two EBooks 51 Recipes using jQuery with ASP.NET Controls. and The Absolutely Awesome jQuery CookBook

Follow him on twitter @suprotimagarwal

No comments: