how to add textboxes to webform in runtime(dynamically)


design the webform as follows:

  1. <html xmlns="http://www.w3.org/1999/xhtml"&gt;
  2. <head id="Head1" runat="server">
  3. <title></title>
  4. </head>
  5. <body>
  6. <form id="form1" runat="server">
  7. <div>
  8.  
  9. <asp:Button ID="Button1" runat="server" onclick="Button1_Click"
  10. style="font-weight: 700" Text="Click to add textbox" />
  11.  
  12. </div>
  13. <asp:PlaceHolder ID="PlaceHolder1" runat="server"></asp:PlaceHolder>
  14. </form>
  15. </body>
  16. </html>

write codebehind as follows:

  1. using System;
  2. using System.Collections.Generic;
  3. using System.Linq;
  4. using System.Web;
  5. using System.Web.UI;
  6. using System.Web.UI.WebControls;
  7.  
  8. public partial class _Default : System.Web.UI.Page
  9. {
  10.     protected void Page_Load(object sender, EventArgs e)
  11.     {
  12.     }
  13.     int count;
  14.     protected void Button1_Click(object sender, EventArgs e)
  15.     {
  16.         if (ViewState["tbno"] != null)
  17.         {
  18.             count = (int)ViewState["tbno"];
  19.             for (int i = 0; i < count; i++)
  20.             {
  21.                 TextBox tb = new TextBox();
  22.                 tb.ID = "tb" + ViewState["tbno"];
  23.                 PlaceHolder1.Controls.Add(tb);
  24.             }
  25.             ViewState["tbno"] = Convert.ToInt16(ViewState["tbno"]) + 1;
  26.         }
  27.         else
  28.         {
  29.             TextBox tb0 = new TextBox();
  30.             PlaceHolder1.Controls.Add(tb0);
  31.             ViewState["tbno"] = 2;
  32.         }
  33.     }
  34. }

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s