Click here to Skip to main content
15,891,597 members
Please Sign up or sign in to vote.
1.00/5 (1 vote)
See more:
i just want a help in coding C# with this scenario:

I have textboxes: textbox1, textbox2, textbox3, ... textbox8
i want to save each values / strings inside these textboxes to database using a loop.

thanks
Posted

Use code like below...

<pre lang="c#">
for (int i = 1; i <= 8;i++ )
{
TextBox txtbox;
txtbox = (TextBox)this.FindControl("textbox" + i.ToString());
//write your code for save values
}
 
Share this answer
 
While you can do exactly that using reflection, it's a cumbersome and slow way to do it. You would probably be better off either lopping through all controls on your form and identifying TextBoxes, or setting up an array of TextBoxes you are interested in and lopping through that.

It really depends on what you need to do: of you want the textbooks contents to go to the same row, then that is one thing, if you want them in different rows, then that is quite another.
 
Share this answer
 
you can loop through
C#
Form.Controls
and check for the type of the control
C#
.GetType().FullName == "System.Web.UI.TextBox"
, then take the value.
 
Share this answer
 
As Griff said, you can loop through all controls and check if it is textbox. Below is an example

C#
foreach (Control ctrl in this.Controls)
{
   if (ctrl.GetType().Equals(typeof(TextBox)))
   {
       //You can cast ctrl to TextBox and then extract the data that you need from it
   }
}
 
Share this answer
 
Comments
macmacmacmac 16-Aug-13 2:53am    
hmm. there are other textboxes that might interfere if i use foreach. is that so? can i just loop thru textbox names? like textbox[index].Text??
walterhevedeich 16-Aug-13 3:28am    
You can only access through index if you have put all your textboxes in an array. As for the foreach statement, once you got the control inside that condition, just cast it to a Textbox control. And from there, you can just create another condition that will execute the code if that is the textbox that you want (i.e. you can probably check the name of each of the textboxes). I have to warn you though of possible performance issues because of the loop and the conditions.

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900