By using this site, you agree to our updated Privacy Policy and our Terms of Use. Manage your Cookies Settings.
449,215 Members | 1,934 Online
Bytes IT Community
+ Ask a Question
Need help? Post your question and get tips & solutions from a community of 449,215 IT Pros & Developers. It's quick & easy.

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

P: 22
good evening...

how can store the text value of dynamically created textbox in database.
Expand|Select|Wrap|Line Numbers
  1. using System; 
  2. using System.Data; 
  3. using System.Configuration; 
  4. using System.Collections; 
  5. using System.Web; 
  6. using System.Web.Security; 
  7. using System.Web.UI; 
  8. using System.Web.UI.WebControls; 
  9. using System.Web.UI.WebControls.WebParts; 
  10. using System.Web.UI.HtmlControls; 
  11. using System.Data.SqlClient; 
  12. public partial class frndslambook : System.Web.UI.Page 
  13.     SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["ConnectionString"].ConnectionString); 
  14.      SqlCommand com1; 
  15.     SqlCommand com; 
  16.     SqlDataReader dr1; 
  17.     static string[] exp; 
  18.      static string exp1; 
  19.     static long c; 
  20.     TextBox[] textBoxArr = new TextBox[c + 1];   
  21.     protected void Page_Load(object sender, EventArgs e) 
  22.     { 
  23.        com1 = new SqlCommand("Select * From slambook Where username=@username", con); 
  24.      com1.Parameters.Add("@username", SqlDbType.NVarChar).Value = Session["userfrndname"].ToString(); 
  25.         try 
  26.         { 
  27.             if (con.State == ConnectionState.Closed) 
  28.                 con.Open(); 
  29.             dr1 = com1.ExecuteReader(); 
  30.             if (dr1.Read()) 
  31.             { 
  32.  
  33.  
  34.                 string exp1 = dr1["slambookfields"].ToString(); 
  35.                long c = Convert.ToInt64(exp1.Length); 
  36.                 Label[] l1 = new Label[c + 1];//array of lables 
  37.               TextBox[] textBoxArr = new TextBox[c + 1];//array of textboxes 
  38.  
  39.                 exp = (exp1).Trim('^').Split('^'); 
  40.                 for (int i = 0; i < exp.Length; i++) 
  41.                 { 
  42.                     Panel frndstextBoxLabelGroup = new Panel(); 
  43.                     l1[i] = new Label(); 
  44.                     l1[i].ID = "frndslambooklabel" + i.ToString(); 
  45.                     l1[i].Text = exp[i].ToString(); 
  46.                     l1[i].Visible = true; 
  47.  
  48.  
  49.                     textBoxArr[i] = new TextBox(); 
  50.                     textBoxArr[i].ID = "frndslambooktextbox" + i.ToString(); 
  51.                     textBoxArr[i].Visible = true; 
  52.                     //Initializing the TextBox so that it is not rendered in the browser 
  53.                     frndstextBoxLabelGroup.ID = "frndstextBoxLabelGroup" + i.ToString(); 
  54.                     fspfrndslambook.Visible = true; 
  55.                     // Pnl_TextBox.Controls.Add(br); 
  56.                     frndstextBoxLabelGroup.Controls.Add(l1[i]); 
  57.  
  58.                     frndstextBoxLabelGroup.Controls.Add(textBoxArr[i]); 
  59.                     fspfrndslambook.Controls.Add(frndstextBoxLabelGroup); 
  60.  
  61.  
  62.                 } 
  63.             } 
  64.  
  65.  
  66.         } 
  67.         catch (Exception exc) 
  68.         { 
  69.         } 
  70.         finally 
  71.         { 
  72.             con.Close(); 
  73.         } 
  74.  
  75.     } 
  76.     protected void fsbfill_Click(object sender, EventArgs e) 
  77.     { 
  78.         com = new SqlCommand("Insert Into slambookans (slambookfields_ans,sender,receiver) Values(@slambookfields_ans,@sender,@receiver)", con); 
  79.        for (int i = 0; i < exp.Length; i++) 
  80.         //{ 
  81.             //textBoxArr[i] = new TextBox(); 
  82.          com.Parameters.Add("@slambookfields_ans", SqlDbType.NVarChar).Value =textBoxArr[i].Text; 
  83.  
  84.         } 
  85.         com.Parameters.Add("@sender", SqlDbType.NVarChar).Value = Session["username"].ToString(); 
  86.         com.Parameters.Add("@receiver", SqlDbType.NVarChar).Value = Session["userfrndname"].ToString(); 
  87.              try 
  88.             { 
  89.                 if (con.State == ConnectionState.Closed) 
  90.                     con.Open(); 
  91.                 int i=com.ExecuteNonQuery(); 
  92.                if(i!=0) 
  93.                Response.Write("Success"); 
  94.                else 
  95.                 Response.Write("Fail"); 
  96.              } 
  97.         catch(Exception exc) 
  98.         { 
  99.         } 
  100.         finally 
  101.         { 
  102.             con.Close(); 
  103.         } 
  104.     } 
  105.  
Oct 15 '10 #1
Share this Question
Share on Google+
12 Replies


Frinavale
Expert Mod 5K+
P: 9,731
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
Oct 15 '10 #2

P: 9
I think, The main problem is between these two lines --
line no.51
Expand|Select|Wrap|Line Numbers
  1.   textBoxArr[i].ID = "frndslambooktextbox" + i.ToString();
then Line no.83
Expand|Select|Wrap|Line Numbers
  1. 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 --
Expand|Select|Wrap|Line Numbers
  1. string abc = "frndsslambooktextbox"+i.ToString();
  2. TextBox txt = (TextBox)pnl1.FindControl("abc");
  3. com.Parameters.Add("@slambookfields_ans",SqlDbType.NVarChar).Value=txt.Text;
Hope this Helps.
Happy Coding.
Oct 17 '10 #3

P: 22
the problem is not resolved after changing the 83 line.it gave the "Null Referance exception"
please help me...for solving this exception..
Oct 18 '10 #4

P: 9
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.FindControl("textboxid");

Follow the concept, not the code ...

Happy Coding
Oct 18 '10 #5

Frinavale
Expert Mod 5K+
P: 9,731
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
Oct 18 '10 #6

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

Frinavale
Expert Mod 5K+
P: 9,731
It's actually not a "problem"...that 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 SelectedIndexChanged 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
Oct 18 '10 #8

P: 9
Sorry, my mistake ..
In my previous post all was fine expect .. the double quotes. So remove that
Expand|Select|Wrap|Line Numbers
  1. string abc = "frndsslambooktextbox"+i.ToString();
  2. //Change this: TextBox txt = (TextBox)pnl1.FindControl("abc");
  3. //To this:
  4. 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
Oct 18 '10 #9

Frinavale
Expert Mod 5K+
P: 9,731
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
Oct 19 '10 #10

P: 9
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.
Oct 19 '10 #11

P: 22
good evening sir..

i changed the "abc" to abc but still the null referance exeception is remain same."TextBox txt = (TextBox)pnl1.FindControl(abc); " contain null value at run time the code is now as..
Expand|Select|Wrap|Line Numbers
  1. using System;
  2. using System.Data;
  3. using System.Configuration;
  4. using System.Collections;
  5. using System.Web;
  6. using System.Web.Security;
  7. using System.Web.UI;
  8. using System.Web.UI.WebControls;
  9. using System.Web.UI.WebControls.WebParts;
  10. using System.Web.UI.HtmlControls;
  11. using System.Data.SqlClient;
  12. public partial class frndslambook : System.Web.UI.Page
  13. {
  14.     SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["ConnectionString"].ConnectionString);
  15.      SqlCommand com1;
  16.     SqlCommand com;
  17.     SqlDataReader dr1;
  18.     static string[] exp;
  19.      static string exp1;
  20.     static long c;
  21.      TextBox[] textBoxArr = new TextBox[c + 1]; 
  22.     protected void Page_Load(object sender, EventArgs e)
  23.     {
  24.  
  25.        com1 = new SqlCommand("Select * From slambook Where username=@username", con);
  26.      com1.Parameters.Add("@username", SqlDbType.NVarChar).Value = Session["userfrndname"].ToString();
  27.         try
  28.         {
  29.             if (con.State == ConnectionState.Closed)
  30.                 con.Open();
  31.             dr1 = com1.ExecuteReader();
  32.             if (dr1.Read())
  33.             {
  34.                 string exp1 = dr1["slambookfields"].ToString();
  35.                long c = Convert.ToInt64(exp1.Length);
  36.                 Label[] l1 = new Label[c + 1];//array of lables
  37.                TextBox[] textBoxArr = new TextBox[c + 1];//array of textboxes
  38.                 exp = (exp1).Trim('^').Split('^');
  39.                 for (int i = 0; i < exp.Length; i++)
  40.                 {
  41.                  Panel frndstextBoxLabelGroup = new Panel();
  42.                     l1[i] = new Label();
  43.                     l1[i].ID = "frndslambooklabel" + i.ToString();
  44.                     l1[i].Text = exp[i].ToString();
  45.                     l1[i].Visible = true;
  46.                     textBoxArr[i] = new TextBox();
  47.                     textBoxArr[i].ID = "frndslambooktextbox" + i.ToString();
  48.                     textBoxArr[i].Visible = true;
  49.                    //Initializing the TextBox so that it is not rendered in the browser
  50.                    frndstextBoxLabelGroup = new Panel();
  51.                    frndstextBoxLabelGroup.ID = "frndstextBoxLabelGroup" + i.ToString();
  52.                     fspfrndslambook.Visible = true;
  53.                     // Pnl_TextBox.Controls.Add(br);
  54.                     frndstextBoxLabelGroup.Controls.Add(l1[i]);
  55.                    frndstextBoxLabelGroup.Controls.Add(textBoxArr[i]);
  56.                     fspfrndslambook.Controls.Add(frndstextBoxLabelGroup);
  57.                 }
  58.             }
  59.         }
  60.         catch (Exception exc)
  61.         {
  62.         }
  63.         finally
  64.         {
  65.             con.Close();
  66.         }
  67.  
  68.     }
  69.  
  70.  
  71.     protected void fsbfill_Click(object sender, EventArgs e)
  72.     {
  73.         com = new SqlCommand("Insert Into slambookans (slambookfields_ans,sender,receiver) Values(@slambookfields_ans,@sender,@receiver)", con);
  74.         for (int i = 0; i < exp.Length; i++)
  75.          {
  76.           string abc = "frndsslambooktextbox" + i.ToString();
  77.           TextBox txt = (TextBox)fspfrndslambook.FindControl(abc);
  78.           com.Parameters.Add("@slambookfields_ans", SqlDbType.NVarChar).Value = txt.Text; 
  79.          }
  80.         com.Parameters.Add("@sender", SqlDbType.NVarChar).Value = Session["username"].ToString();
  81.         com.Parameters.Add("@receiver", SqlDbType.NVarChar).Value = Session["userfrndname"].ToString();
  82.              try
  83.             {
  84.                 if (con.State == ConnectionState.Closed)
  85.                     con.Open();
  86.                 int i=com.ExecuteNonQuery();
  87.                if(i!=0)
  88.                Response.Write("Success");
  89.                else
  90.                 Response.Write("Fail");
  91.              }
  92.         catch(Exception exc)
  93.         {
  94.         }
  95.         finally
  96.         {
  97.             con.Close();
  98.         }
  99.     }
  100.  
  101.  
  102. }
  103.  
Oct 20 '10 #12

P: 9
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
Oct 22 '10 #13

Post your reply

Sign in to post your reply or Sign up for a free account.