How can save the dynamically created textbox value in database..?

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • pooja8389
    New Member
    • Sep 2010
    • 22

    How can save the dynamically created textbox value in database..?

    good evening...

    how can store the text value of dynamically created textbox in database.
    Code:
    using System; 
    using System.Data; 
    using System.Configuration; 
    using System.Collections; 
    using System.Web; 
    using System.Web.Security; 
    using System.Web.UI; 
    using System.Web.UI.WebControls; 
    using System.Web.UI.WebControls.WebParts; 
    using System.Web.UI.HtmlControls; 
    using System.Data.SqlClient; 
    public partial class frndslambook : System.Web.UI.Page 
    { 
        SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["ConnectionString"].ConnectionString); 
         SqlCommand com1; 
        SqlCommand com; 
        SqlDataReader dr1; 
        static string[] exp; 
         static string exp1; 
        static long c; 
        TextBox[] textBoxArr = new TextBox[c + 1];   
        protected void Page_Load(object sender, EventArgs e) 
        { 
           com1 = new SqlCommand("Select * From slambook Where username=@username", con); 
         com1.Parameters.Add("@username", SqlDbType.NVarChar).Value = Session["userfrndname"].ToString(); 
            try 
            { 
                if (con.State == ConnectionState.Closed) 
                    con.Open(); 
                dr1 = com1.ExecuteReader(); 
                if (dr1.Read()) 
                { 
      
      
                    string exp1 = dr1["slambookfields"].ToString(); 
                   long c = Convert.ToInt64(exp1.Length); 
                    Label[] l1 = new Label[c + 1];//array of lables 
                  TextBox[] textBoxArr = new TextBox[c + 1];//array of textboxes 
      
                    exp = (exp1).Trim('^').Split('^'); 
                    for (int i = 0; i < exp.Length; i++) 
                    { 
                        Panel frndstextBoxLabelGroup = new Panel(); 
                        l1[i] = new Label(); 
                        l1[i].ID = "frndslambooklabel" + i.ToString(); 
                        l1[i].Text = exp[i].ToString(); 
                        l1[i].Visible = true; 
      
      
                        textBoxArr[i] = new TextBox(); 
                        textBoxArr[i].ID = "frndslambooktextbox" + i.ToString(); 
                        textBoxArr[i].Visible = true; 
                        //Initializing the TextBox so that it is not rendered in the browser 
                        frndstextBoxLabelGroup.ID = "frndstextBoxLabelGroup" + i.ToString(); 
                        fspfrndslambook.Visible = true; 
                        // Pnl_TextBox.Controls.Add(br); 
                        frndstextBoxLabelGroup.Controls.Add(l1[i]); 
      
                        frndstextBoxLabelGroup.Controls.Add(textBoxArr[i]); 
                        fspfrndslambook.Controls.Add(frndstextBoxLabelGroup); 
      
      
                    } 
                } 
      
      
            } 
            catch (Exception exc) 
            { 
            } 
            finally 
            { 
                con.Close(); 
            } 
      
        } 
        protected void fsbfill_Click(object sender, EventArgs e) 
        { 
            com = new SqlCommand("Insert Into slambookans (slambookfields_ans,sender,receiver) Values(@slambookfields_ans,@sender,@receiver)", con); 
           for (int i = 0; i < exp.Length; i++) 
            //{ 
                //textBoxArr[i] = new TextBox(); 
             com.Parameters.Add("@slambookfields_ans", SqlDbType.NVarChar).Value =textBoxArr[i].Text; 
      
            } 
            com.Parameters.Add("@sender", SqlDbType.NVarChar).Value = Session["username"].ToString(); 
            com.Parameters.Add("@receiver", SqlDbType.NVarChar).Value = Session["userfrndname"].ToString(); 
                 try 
                { 
                    if (con.State == ConnectionState.Closed) 
                        con.Open(); 
                    int i=com.ExecuteNonQuery(); 
                   if(i!=0) 
                   Response.Write("Success"); 
                   else 
                    Response.Write("Fail"); 
                 } 
            catch(Exception exc) 
            { 
            } 
            finally 
            { 
                con.Close(); 
            } 
        } 
    }
  • Frinavale
    Recognized Expert Expert
    • Oct 2006
    • 9749

    #2
    There's quite a few things that could possibly be causing you problems. It would be best if you stated what you are having problems with.

    -Frinny

    Comment

    • abhinavpratap
      New Member
      • Sep 2010
      • 9

      #3
      I think, The main problem is between these two lines --
      line no.51
      Code:
        textBoxArr[i].ID = "frndslambooktextbox" + i.ToString();
      then Line no.83
      Code:
      com.Parameters.Add("@slambookfields_ans", SqlDbType.NVarChar).Value =textBoxArr[i].Text;
      So to solve this ---
      You should first find that control be on page or inside a panel. Cast to a textbox. Then use the TextBox.Text Property.

      Like this --
      Code:
      string abc = "frndsslambooktextbox"+i.ToString();
      TextBox txt = (TextBox)pnl1.FindControl("abc");
      com.Parameters.Add("@slambookfields_ans",SqlDbType.NVarChar).Value=txt.Text;
      Hope this Helps.
      Happy Coding.

      Comment

      • pooja8389
        New Member
        • Sep 2010
        • 22

        #4
        the problem is not resolved after changing the 83 line.it gave the "Null Referance exception"
        please help me...for solving this exception..

        Comment

        • abhinavpratap
          New Member
          • Sep 2010
          • 9

          #5
          debug it , the FindControl() method is not finding the textboxes.

          Find it yourself, as it is not clear from your code whether textboxes are on page or in panel.
          If on page use Page.FindContro l("textboxid" );

          Follow the concept, not the code ...

          Happy Coding

          Comment

          • Frinavale
            Recognized Expert Expert
            • Oct 2006
            • 9749

            #6
            You should look over the article titled "How to use Dynamic Controls in ASP.NET"

            It will show you how to properly add dynamic controls to your web page.

            Right now you are creating your TextBoxes in your Page Load event...they are not going to contain the information the user provided because this should have been done in the Page Init event.

            -Frinny

            Comment

            • pooja8389
              New Member
              • Sep 2010
              • 22

              #7
              actually the pageload function is executing every time when i click on "fsbfill_Click( )" button .please tell me how can i resolve this problem?

              Comment

              • Frinavale
                Recognized Expert Expert
                • Oct 2006
                • 9749

                #8
                It's actually not a "problem"...tha t is how it is supposed to work.

                Did you read over the Microsoft documentation on the topic of the ASP.NET Life Cycle?

                In general this is what happens:
                • Browser makes a request to the server for an .aspx page
                • The server passes the request to ASP.NET so that it can execute the page requested
                • The Page's code is executed in this order:
                  • The Page Init event is fired: the page is Initialization. ..all of the objects required in order to process the request are created/instantiated at this point.
                  • The ViewState is loaded for all of the controls on the page. This is the step where all of the objects are loaded with user information etc...it is also the step where events are created based on the user's actions
                  • The Page Load event is fired
                  • All Postback events are handled. This includes any events that originated from any controls on the page. For example a Button Click event or a DropDownList SelectedIndexCh anged event
                  • The Page PreRender event occurs. This is the last time that you can access any controls on the page before the HTML is generated based on the controls.
                  • The Render event occurs: HTML is generated based on the controls.
                  • The Response is sent to the browser
                  • All objects/controls are destroyed.


                So, if you have code in the Page Load event it will be executed Every time a request occurs.

                You can use the Page.IsPostback Property to determine if it is the first time the page is loading. The Page.IsPostback property is loaded with True or False when the ViewState is loaded (therefore it is not available in the Page Init Event...it will always be false at that point).

                If the Page.IsPostback property is True it means that the request was caused by a control on the page which needed to "Post back" to the server for server-side processing. If Page.IsPostback is False then it is the first time the page is loading.

                So, to resolve you problem...you should check if the Page.IsPostback property is "False" (which indicates it's the first time the page is loading) and call the appropriate code.


                I seriously recommend that you Read the article I linked you to earlier because you are using Dynamic Controls.

                You should not be creating dynamic controls in the Page Load event because they their ViewState and any events will not be loaded and your page will not execute properly.

                You should always be instantiating your dynamic controls (every page request) in the Page Init event or you could run into problems with "page validation" problems.

                Since you don't know about the ASP.NET Life Cycle...I recommend that you do not use dynamic controls.

                I recommend that you add the controls to the page by dragging them out of the toolbox onto the page.

                You can set the Visible properties of the controls so that only certain controls are displayed to the user...when you set the Visible property to false in your C# or VB.NET server-side code, the HTML is not rendered in the browser...so the user will never see it unless you set the Visible property to true.

                -Frinny
                Last edited by Frinavale; Oct 19 '10, 01:39 PM.

                Comment

                • abhinavpratap
                  New Member
                  • Sep 2010
                  • 9

                  #9
                  Sorry, my mistake ..
                  In my previous post all was fine expect .. the double quotes. So remove that
                  Code:
                  string abc = "frndsslambooktextbox"+i.ToString();
                  //Change this: TextBox txt = (TextBox)pnl1.FindControl("abc");
                  //To this:
                  TextBox txt = (TextBox)pnl1.FindControl(abc);
                  I have tested this, It will surely help..
                  In my previous post I accept null refernce exception was coming due to this.

                  Don't worry about page loads..

                  Hope this helps,
                  Happy Coding
                  Last edited by Frinavale; Oct 19 '10, 08:07 PM. Reason: Added relevant code that clarifies the explanation.

                  Comment

                  • Frinavale
                    Recognized Expert Expert
                    • Oct 2006
                    • 9749

                    #10
                    Abhinavpratap,


                    (Edit: I fixed the original post so that it makes more sense...it now shows what "abc" is...)

                    The FindControl() method takes a String as a parameter. This means that you have to pass it a String...

                    In the code that you just posted you are not passing a String...you are passing a variable named abc (I think...if not then your code just will not work)

                    You should be using double quotes because double quotes indicate a String.

                    If the FindControl() method cannot find the control that you have requested then it will return Null (or in VB.NET Nothing). If you do not check to see if the control is Null/Nothing before using it, there is a possibility of a Null Exception being thrown.

                    -Frinny
                    Last edited by Frinavale; Oct 19 '10, 08:31 PM.

                    Comment

                    • abhinavpratap
                      New Member
                      • Sep 2010
                      • 9

                      #11
                      You are right Frinny, but I think you haven't seen my lines above. I have posted 3 times on this thread #3,#5,#9 and now. In the #9 reply i have just corrected #3 reply.

                      Comment

                      • pooja8389
                        New Member
                        • Sep 2010
                        • 22

                        #12
                        good evening sir..

                        i changed the "abc" to abc but still the null referance exeception is remain same."TextBox txt = (TextBox)pnl1.F indControl(abc) ; " contain null value at run time the code is now as..
                        Code:
                        using System;
                        using System.Data;
                        using System.Configuration;
                        using System.Collections;
                        using System.Web;
                        using System.Web.Security;
                        using System.Web.UI;
                        using System.Web.UI.WebControls;
                        using System.Web.UI.WebControls.WebParts;
                        using System.Web.UI.HtmlControls;
                        using System.Data.SqlClient;
                        public partial class frndslambook : System.Web.UI.Page
                        {
                            SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["ConnectionString"].ConnectionString);
                             SqlCommand com1;
                            SqlCommand com;
                            SqlDataReader dr1;
                            static string[] exp;
                             static string exp1;
                            static long c;
                             TextBox[] textBoxArr = new TextBox[c + 1]; 
                            protected void Page_Load(object sender, EventArgs e)
                            {
                                
                               com1 = new SqlCommand("Select * From slambook Where username=@username", con);
                             com1.Parameters.Add("@username", SqlDbType.NVarChar).Value = Session["userfrndname"].ToString();
                                try
                                {
                                    if (con.State == ConnectionState.Closed)
                                        con.Open();
                                    dr1 = com1.ExecuteReader();
                                    if (dr1.Read())
                                    {
                                        string exp1 = dr1["slambookfields"].ToString();
                                       long c = Convert.ToInt64(exp1.Length);
                                        Label[] l1 = new Label[c + 1];//array of lables
                                       TextBox[] textBoxArr = new TextBox[c + 1];//array of textboxes
                                        exp = (exp1).Trim('^').Split('^');
                                        for (int i = 0; i < exp.Length; i++)
                                        {
                                         Panel frndstextBoxLabelGroup = new Panel();
                                            l1[i] = new Label();
                                            l1[i].ID = "frndslambooklabel" + i.ToString();
                                            l1[i].Text = exp[i].ToString();
                                            l1[i].Visible = true;
                                            textBoxArr[i] = new TextBox();
                                            textBoxArr[i].ID = "frndslambooktextbox" + i.ToString();
                                            textBoxArr[i].Visible = true;
                                           //Initializing the TextBox so that it is not rendered in the browser
                                           frndstextBoxLabelGroup = new Panel();
                                           frndstextBoxLabelGroup.ID = "frndstextBoxLabelGroup" + i.ToString();
                                            fspfrndslambook.Visible = true;
                                            // Pnl_TextBox.Controls.Add(br);
                                            frndstextBoxLabelGroup.Controls.Add(l1[i]);
                                           frndstextBoxLabelGroup.Controls.Add(textBoxArr[i]);
                                            fspfrndslambook.Controls.Add(frndstextBoxLabelGroup);
                                        }
                                    }
                                }
                                catch (Exception exc)
                                {
                                }
                                finally
                                {
                                    con.Close();
                                }
                        
                            }
                           
                            
                            protected void fsbfill_Click(object sender, EventArgs e)
                            {
                                com = new SqlCommand("Insert Into slambookans (slambookfields_ans,sender,receiver) Values(@slambookfields_ans,@sender,@receiver)", con);
                                for (int i = 0; i < exp.Length; i++)
                                 {
                                  string abc = "frndsslambooktextbox" + i.ToString();
                                  TextBox txt = (TextBox)fspfrndslambook.FindControl(abc);
                                  com.Parameters.Add("@slambookfields_ans", SqlDbType.NVarChar).Value = txt.Text; 
                                 }
                                com.Parameters.Add("@sender", SqlDbType.NVarChar).Value = Session["username"].ToString();
                                com.Parameters.Add("@receiver", SqlDbType.NVarChar).Value = Session["userfrndname"].ToString();
                                     try
                                    {
                                        if (con.State == ConnectionState.Closed)
                                            con.Open();
                                        int i=com.ExecuteNonQuery();
                                       if(i!=0)
                                       Response.Write("Success");
                                       else
                                        Response.Write("Fail");
                                     }
                                catch(Exception exc)
                                {
                                }
                                finally
                                {
                                    con.Close();
                                }
                            }
                        
                        
                        }

                        Comment

                        • abhinavpratap
                          New Member
                          • Sep 2010
                          • 9

                          #13
                          Can't say , why it didn't worked for u.
                          But I have made similar test sample and it worked well.
                          I have attached it as well.

                          Bytes_dynamicTextBox.zip

                          Hope this helps,
                          Happy Coding

                          Comment

                          Working...