0

In my website I am uploading photos through asp:FileUpload [multiple files - images].. After uploading I am displaying them in a Panel along with a textbox to write description for the uploaded Images. Then am going to save them in database. But I am not able to find the values of the textbox or find the controls I have added to the panel when in my save event. But the images and textbox will be displayed in the panel.

My frontend code is something like this:

  <form id="form1" runat="server">
    <div class="transbox" id="mainbk" runat="server" style="position:absolute; top:0px; left:0px; width: 100%; height: 100%;" >
      <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"/>
        <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" />
        <asp:Panel ID="updtpanel" runat="server" CssClass="transbox" style="width:100%;height:100%;left:0px;top:0px;position:absolute" Visible="false">
             <asp:Button ID="btnsave" runat="server" Text="Save" OnClick="btnsave_Click" Font-Bold="true" BackColor="Yellow" />
        </asp:Panel>
     </div>
  </form>

and my backend code is something like this:

protected void uploadFile_Click(object sender, EventArgs e)
    {
        if (UploadImages.HasFiles)
        {
           int tid = 0;

           string fileExt = Path.GetExtension(UploadImages.FileName).ToLower();
           if (fileExt == ".jpeg" || fileExt == ".png" || fileExt == ".jpg" || fileExt == ".bmp")
           {
               HtmlGenericControl dh = new HtmlGenericControl("div");
               dh.Attributes.Add("class", "head");
               dh.InnerText = "Write Description";
               updtpanel.Controls.Add(dh);

               HtmlGenericControl dload;
               foreach (HttpPostedFile uploadedFile in UploadImages.PostedFiles)
               {
                   tid = tid + 1;
                   textid = "txt" + tid;
                   Image img = new Image();
                   TextBox ta = new TextBox();
                   ta.TextMode = TextBoxMode.MultiLine;
                   filepath = Server.MapPath("~/Images/Gallery/" + uploadedFile.FileName);
                   uploadedFile.SaveAs(filepath);
                   newpath = "../Images/Gallery/" + uploadedFile.FileName;
                   try
                   {
                       dload = new HtmlGenericControl("div");
                       updtpanel.Visible = true;
                       dload.Attributes.Add("class", "dataload");
                       dload.Attributes.Add("runat", "server");
                       dload.ID = "ind" + tid;
                       img.CssClass = "loadimg";
                       img.ImageUrl = newpath.ToString();
                       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);
                   }

                   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);        
        }
    }


    protected void btnsave_Click(object sender, EventArgs e)
    {
        foreach (Control c in updtpanel.Controls) 
        {
            cnt1 += 1;
            HtmlGenericControl div = ((HtmlGenericControl)updtpanel.FindControl("ind"+cnt1.ToString()));
            foreach (Control nc in div.Controls)
            {
                string str = "";
                string iurl = "";
                TextBox txt = (TextBox)div.FindControl("txt" + cnt1.ToString());
                Image img = (Image)div.FindControl("img" + cnt1.ToString());
                str = txt.Text;
                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;
    }

But its giving an error while saving which says object reference not set to an instance of the object after Findcontrol in save click event. Where I am going wrong. I am really working this from past 3 days but still not able to get it. Please show me a way out of this.

Is there anything else I need to add to this? I came across some site where some of them said that controls need to be recreated in Page_Load after postback. But when I am creating controls in an event How can I recreate them back in Page_Load.

Guruprasad J Rao
  • 29,410
  • 14
  • 101
  • 200

1 Answers1

1

Try this.Works for me try replacing the contentplaceholder with the form id may work.

  String Value=   (this.Form.FindControl("ContentPlaceHolder1").FindControl("panel").FindControl("txtbx" ) as TextBox).Text;
Karthik
  • 2,391
  • 6
  • 34
  • 65
  • @Karthik.. Its still giving the same error.. It is not finding the control itself... :( – Guruprasad J Rao Jul 10 '13 at 06:03
  • use quickwatch check by inspecting each find control and detect which returns null..thats how i debugged it – Karthik Jul 10 '13 at 06:27
  • @Karthik... actually the textbox itself returns null and when I inspect it in browser the textbox will be there with proper ID.. I dont know why it is not able to find the textbox itself... n the Textbox which I create here when watched in browser will be declared as html textarea... :( – Guruprasad J Rao Jul 10 '13 at 07:52
  • no debug it part by part first debug this.Form.FindControl("ContentPlaceHolder1") then this.Form.FindControl("ContentPlaceHolder1").FindControl("panel") and so on this will help you to know which control is inaccessible or returns null – Karthik Jul 10 '13 at 08:59
  • @Karthik.. I debugged it and Until Panel I will get the control but later on div, which I add dynamically, it returns null... :( – Guruprasad J Rao Jul 10 '13 at 17:50
  • did you try adding div to find control ? – Karthik Jul 11 '13 at 04:34