title: Dynamically adding textbox on button click in ASP .NET
body: <p>I'm follow this code from youtube, but this code not work for me..</p>
  <pre><code>&lt;body&gt;
      &lt;form id=&quot;form1&quot; runat=&quot;server&quot;&gt;
      &lt;div&gt;
          &lt;asp:Button ID=&quot;Button1&quot; runat=&quot;server&quot; Text=&quot;Button&quot; OnClick=&quot;Button1_Click&quot; /&gt;
          &lt;asp:PlaceHolder ID=&quot;PlaceHolder1&quot; runat=&quot;server&quot;&gt;&lt;/asp:PlaceHolder&gt;
      &lt;/div&gt;        
      &lt;/form&gt; &lt;/body&gt;
  </code></pre>
  <p>here the code behind</p>
  <pre><code>  using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Web;
    using System.Web.UI;
    using System.Web.UI.WebControls;
  
  
   namespace WebApplication4
  {
   public partial class WebForm1 : System.Web.UI.Page
  {
      List&lt;string&gt; controlIdList = new List&lt;string&gt;();
      int counter = 0;
      protected override void LoadViewState(object savedState)
      {
          base.LoadViewState(savedState);   
          
          controlIdList = (List&lt;string&gt;)ViewState[&quot;contrloIdList&quot;];
          foreach (string Id in controlIdList)
          {
              counter++;
              TextBox tb = new TextBox();
              tb.ID = Id;
              LiteralControl lineBreak = new LiteralControl();
              PlaceHolder1.Controls.Add(tb);
              PlaceHolder1.Controls.Add(lineBreak);
          }
      }
      protected void Page_Load(object sender, EventArgs e)
      {
  
      }
  
      protected void Button1_Click(object sender, EventArgs e)
      {
          counter++;
          TextBox tb = new TextBox();
          tb.ID = &quot;textbox&quot; + counter;
          tb.Text = &quot;new textbox&quot;;
  
          LiteralControl lineBreak = new LiteralControl(&quot;&lt;br /&gt;&quot;);
          PlaceHolder1.Controls.Add(tb);
          PlaceHolder1.Controls.Add(lineBreak);
          controlIdList.Add(tb.ID);
          ViewState[&quot;controlIdList&quot;] = controlIdList;
      }
  }}
  </code></pre>
  <p>the error is</p>
  <blockquote>
  <p>Description: An unhandled exception occurred during the execution of
  the current web request. Please review the stack trace for more
  information about the error and where it originated in the code.</p>
  <p>Exception Details: System.NullReferenceException: Object reference
  not set to an instance of an object.</p>
  <p>Line 17:</p>
  <p>Line 18:             controlIdList =(List)ViewState[&quot;contrloIdList&quot;];
  Blockquote</p>
  <p>Line 19:             foreach (string Id in controlIdList)</p>
  <p>Line 20:             {</p>
  <p>Line 21:                 counter++;</p>
  </blockquote>