473,407 Members | 2,326 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,407 software developers and data experts.

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

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
12 18073
Frinavale
9,735 Expert Mod 8TB
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
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
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
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
9,735 Expert Mod 8TB
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
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
9,735 Expert Mod 8TB
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
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
9,735 Expert Mod 8TB
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
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
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
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

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

Similar topics

2
by: utterberg | last post by:
Can anyone help me with this problem? I dynamically creates several textboxes using a placeholder. This works fine. But is there a way for me to loop through theese textboxes and retrive its value...
5
by: Jack Johnston | last post by:
Hi there, I am dynamically created a table at runtime on an aspx form. The last cell of each row contains a TextBox in which the user will enter numeric values into. Each textbox I create is...
2
by: JaM | last post by:
Hi all, I have created a gridview vith dynamic textbox columns (they are in variable number, it depends on what things I select from database) aspx code:...
0
by: Silver Oak | last post by:
I have a DataGrid in which one of the columns is TemplateColumn that was created dynamically using iTemplate. I would like to have multi-row editing capability on the DataGrid. I'm trying to...
2
by: HHAAPPYY | last post by:
Hi I am trying to pass value of the textbox along with another value to the query string. when i am retriving the txtbox value it always shows me null, my senario is like this On my...
3
by: raghulvarma | last post by:
I have created only one object for the textbox and that particular textbox is being repeated as many times I want.But if I want to add the values in the database from each and every textbox which...
1
coolv
by: coolv | last post by:
Hello everyone, I m generating dynamic textbox depending on the value selected from the dropdownlist(DropDownList1_SelectedIndexChanged).eg: if i select 3 from dropdownlist,then 3 textbox...
1
by: manila | last post by:
Can u help me I have already created the dynamic textbox.but i don't know the code to insert the records and save it in database through this textbox.
4
by: pooja8389 | last post by:
Good evening.. how can i save the value of dynamically created textbox in data base using System; using System.Data; using System.Configuration; using System.Collections; using...
0
by: emmanuelkatto | last post by:
Hi All, I am Emmanuel katto from Uganda. I want to ask what challenges you've faced while migrating a website to cloud. Please let me know. Thanks! Emmanuel
0
BarryA
by: BarryA | last post by:
What are the essential steps and strategies outlined in the Data Structures and Algorithms (DSA) roadmap for aspiring data scientists? How can individuals effectively utilize this roadmap to progress...
1
by: nemocccc | last post by:
hello, everyone, I want to develop a software for my android phone for daily needs, any suggestions?
1
by: Sonnysonu | last post by:
This is the data of csv file 1 2 3 1 2 3 1 2 3 1 2 3 2 3 2 3 3 the lengths should be different i have to store the data by column-wise with in the specific length. suppose the i have to...
0
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However,...
0
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can...
0
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven...
0
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each...
0
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing,...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.