title: Error in finding dynamic created control
body: <p>I am uploading images using Fileupload control and after loading the file when I click Upload button the file will be saved in a folder in server, but before saving into database I need to add Image description along with the image.. But I dont know I am getting some error. I am able to save file in folder but when I save it into database only one dynamic added control wil be found and then it will give <strong>Object reference not set to instance of object</strong> Even though there are more than one controls in that particular div. Before going into code I will tell what controls I am adding after I upload the file.. I am adding one image control and textbox for each of the image files I uploaded.. When I upload only one file it will simply go into the foreach loop once again after 1st time.. My code might explain it more.</p>
  
  <p>So this is my .aspx code:</p>
  
  <pre><code>&lt;form id="ContentPlaceHolder1" runat="server"&gt;
  
      &lt;div class="transbox" id="mainbk" runat="server" style="position:absolute; top:0px; left:0px; width: 100%; height: 100%;" &gt;
        &lt;asp:FileUpload runat="server" ID="UploadImages" style="background-color:white; position:absolute; font-family:'Palatino Linotype'; font-size:medium; top: 4px; left: 350px; right: 251px;" Width="500px" AllowMultiple="true"/&gt;
  
          &lt;asp:Button runat="server" ID="uploadedFile" style="position:absolute;  font-family:'Palatino Linotype'; font-size:medium; top: 4px; left: 870px; width: 112px; height: 29px;" Text="Upload" OnClick="uploadFile_Click" /&gt;
          &lt;asp:Panel ID="updtpanel" runat="server" CssClass="transbox" style="width:100%;height:100%;left:0px;top:0px;position:absolute" Visible="false"&gt;
               &lt;asp:Button ID="btnsave" runat="server" UseSubmitBehavior="true" Text="Save" OnClick="btnsave_Click" Font-Bold="true" BackColor="Yellow"&gt;&lt;/asp:Button&gt;
  
          &lt;/asp:Panel&gt;
       &lt;/div&gt;
  
  
      &lt;/form&gt;
  </code></pre>
  
  <p>and this is my backend code.</p>
  
  <pre><code>SqlCommand com = new SqlCommand();
  SqlConnection con = new SqlConnection();
  SqlDataReader reader;
  int id = 0;
  StringBuilder sb = new StringBuilder();
  string filepath = "";
  string newpath = "";
  int tid = 0;
  int count = 0;
  int cnt1 = 0;
  string textid = "";
  Panel dload;
  Image img;
  TextBox ta;
  protected void Page_Load(object sender, EventArgs e)
  {
  
      con.ConnectionString = ConfigurationManager.ConnectionStrings["ConnectionString"].ConnectionString;
      con.Open();
      com = new SqlCommand("select max(slid) from slider", con);
      reader = com.ExecuteReader();
      if (reader.HasRows)
      {
          while (reader.Read())
          {
              id = Convert.ToInt32(reader.GetInt32(0));
          }
      }
      con.Close();
      com.Dispose();
      HtmlGenericControl dh = new HtmlGenericControl("div");
      dh.Attributes.Add("class", "head");
      dh.InnerText = "Write Description";
      updtpanel.Controls.Add(dh);
      foreach (HttpPostedFile upld in UploadImages.PostedFiles)
      {
          createImgPanel();
      }
  }
  
  
  
  protected void uploadFile_Click(object sender, EventArgs e)
  {
      if (UploadImages.HasFiles)
      {
         string fileExt = Path.GetExtension(UploadImages.FileName).ToLower();
         if (fileExt == ".jpeg" || fileExt == ".png" || fileExt == ".jpg" || fileExt == ".bmp")
         {
             foreach (HttpPostedFile uploadedFile in UploadImages.PostedFiles)
             {
                 count += 1;
                 filepath = Server.MapPath("~/Images/Gallery/" + uploadedFile.FileName);
                 uploadedFile.SaveAs(filepath);
                 newpath = "../Images/Gallery/" + uploadedFile.FileName;
                 try
                 {
                     Image nimg = dload.FindControl("img" + count) as Image;
                     nimg.ImageUrl = newpath.ToString();
                 }
  
                 catch (Exception ex)
                 {
                     Response.Write(ex.Message);
                 }
  
             }
         }
         else
         {
             Page.ClientScript.RegisterStartupScript(GetType(), "msgbox", "alert('Please Select only Image Files!!');", true);
         }
  
      }
      else
      {
          Page.ClientScript.RegisterStartupScript(GetType(), "msgbox", "alert('Please Select a File First!!');", true);        
      }
  }
  
  public void createImgPanel()
  {
      tid = tid + 1;
      textid = "txt" + tid;
      ta = new TextBox();
      img = new Image();
      ta.TextMode = TextBoxMode.MultiLine;
      dload = new Panel();
      updtpanel.Visible = true;
      dload.Attributes.Add("class", "dataload");
      //dload.Attributes.Add("runat", "server");
      dload.ID = "ind" + tid;
      img.CssClass = "loadimg";
  
      img.ID = "img" + tid;
      //img.Attributes.Add("runat", "server");
      ta.Attributes.Add("class", "txtdes");
      ta.ID = textid;
      //ta.Attributes.Add("runat", "server");
      dload.Controls.Add(img);
      dload.Controls.Add(ta);
      updtpanel.Controls.Add(dload);
  }
  
  protected void btnsave_Click(object sender, EventArgs e)
  {
      if (Page.IsPostBack)
      {
  
              Panel pv = (this.Form.FindControl("mainbk").FindControl("updtpanel")) as Panel;
  
              foreach (Control cd in pv.Controls)
              {
                  cnt1 = cnt1 + 1;
                  TextBox txt = cd.FindControl("ind" + cnt1).FindControl("txt" + cnt1) as TextBox;****This is where I am getting the above said error****
                  Image img = cd.FindControl("ind" + cnt1).FindControl("img" + cnt1) as Image;
  
                      string str = "";
                      str = txt.Text;
                      string iurl = "";
                      iurl = img.ImageUrl;
  
                      id += 1;
  
                      string Insert = "Insert into slider (slid,slurl,slalt) values (@id,@IMAGE_PATH,@alter)";
                      SqlCommand cmd = new SqlCommand(Insert, con);
                      cmd.Parameters.AddWithValue("@IMAGE_PATH", iurl);
                      cmd.Parameters.AddWithValue("@id", id);
                      cmd.Parameters.AddWithValue("@alter", str);
                      try
                      {
                          con.Open();
                          cmd.ExecuteNonQuery();
                          con.Close();
  
                      }
                      catch (Exception e1)
                      {
                          Response.Write(e1.Message);
                      }
                  }
  
  
  
  
  
          updtpanel.Visible = false;
      }
  }
  </code></pre>
  
  <p>*<strong><em>I am getting error in the last part of above code i.e. save button click event. For Textbox Find control I am getting error. First Image will be saved successfully but for other images its not finding control even if they are present in the design.</em>*</strong></p>
  
  <p><strong>I just want to know whether I am committing any mistakes in save click event or is there any mistake in whole coding itself</strong></p>
  
  <p><strong>Edit</strong></p>
  
  <p>So this is the HTML source after the controls are rendered in runtime:</p>
  
  <pre><code>    &lt;div id="mainbk" class="transbox" style="position:absolute; top:0px; left:0px; width: 100%; height: 100%;"&gt;
            &lt;input type="file" multiple="multiple" name="UploadImages" id="UploadImages" style="width:500px;background-color:white; position:absolute; font-family:'Palatino Linotype'; font-size:medium; top: 4px; left: 350px; right: 251px;"&gt;
  
              &lt;input type="submit" name="uploadedFile" value="Upload" id="uploadedFile" style="position:absolute;  font-family:'Palatino Linotype'; font-size:medium; top: 4px; left: 870px; width: 112px; height: 29px;"&gt;
              &lt;div id="updtpanel" class="transbox" style="width:100%;height:100%;left:0px;top:0px;position:absolute"&gt;
  
                   &lt;input type="submit" name="btnsave" value="Save" id="btnsave" style="background-color:Yellow;font-weight:bold;"&gt;
  
              &lt;div class="head"&gt;Write Description&lt;/div&gt;&lt;div id="ind1" class="dataload"&gt;
              &lt;img id="img1" class="loadimg" runat="server" src="../Images/Gallery/God%201.jpg"&gt;
  &lt;textarea name="txt1" rows="2" cols="20" id="txt1" class="txtdes"&gt;&lt;/textarea&gt;
          &lt;/div&gt;&lt;div id="ind2" class="dataload"&gt;
              &lt;img id="img2" class="loadimg" runat="server" src="../Images/Gallery/God%202.jpg"&gt;
  &lt;textarea name="txt2" rows="2" cols="20" id="txt2" class="txtdes"&gt;&lt;/textarea&gt;
          &lt;/div&gt;&lt;div id="ind3" class="dataload"&gt;
              &lt;img id="img3" class="loadimg" runat="server" src="../Images/Gallery/God%203.jpg"&gt;
  &lt;textarea name="txt3" rows="2" cols="20" id="txt3" class="txtdes"&gt;&lt;/textarea&gt;
          &lt;/div&gt;
      &lt;/div&gt;
           &lt;/div&gt;
  </code></pre>
  
  <p><strong>Edited</strong></p>
  
  <p>K I just went deeper into the exception I am getting... Its saying..</p>
  
  <p><strong>'((System.Web.UI.HtmlControls.HtmlContainerControl)(dv)).InnerHtml' threw an exception of type 'System.Web.HttpException'</strong></p>
  
  <p><strong>What does this actually mean.. Its also says that the control is not literal.. What does that mean.. Why its not able to find the control I have appended..</strong> Help me out please..</p>