2

I am writing a C#/ASP.Net web application and I have a large number of text boxes that need to be set to variable values in the code behind. Currently I am doing the following:

AspTextBox0.Text = codeBehindVariable[0];
AspTextBox1.Text = codeBehindVariable[1];
AspTextBox2.Text = codeBehindVariable[2];
AspTextBox3.Text = codeBehindVariable[3];
… 

Is there an easy way to do this in a simple “for” loop??

This is a very simplified example, the real program has a switch case and some other testing that needs to be performed at the time the variable is assigned. Therefore, a “for” loop would drastically simplify the writing and maintainability of the code. Back in the good-old-days of VB6 and control arrays this was a piece of cake.

John Saunders
  • 160,644
  • 26
  • 247
  • 397
user1751128
  • 21
  • 1
  • 2
  • 2
    A similar posting: http://stackoverflow.com/questions/12150008/add-textbox-text-to-a-list-using-a-for-loop/12150177#12150177 -- you have array on the right, the link has it with the array on the left – JG in SD Oct 16 '12 at 20:12

3 Answers3

6

The good old days of VB6 are long gone and better don't come back.

Create a control array or better a List<TextBox> yourself:

var textBoxes = new List<TextBox> {
    AspTextBox0,
    AspTextBox1,
    // ...
};

Then Zip it with the codeBehindVariable:

textBoxes.Zip(codeBehindVariable, 
              (textBox, variable) => textBox.Text = variable);

Or, if you prefer a for loop:

for ( int i = 0; i < codeBehindVariable.Length; i++ )
{
    textBoxes[i].Text = codeBehindVariable[i];
} 

Keep in mind that in the for loop you will have to make sure that both textBoxes and codeBehindVariable have the same number of items (or make the loop run only over the shortest list's amount of entries). The Zip function will take care of this by itself.

Dennis Traub
  • 50,557
  • 7
  • 93
  • 108
1

Assuming you are in a class that implements System.Web.UI.Page you can try to look up the control to find the one you want like so:

for (int i = 0; i <= codeBehindVariable.Length; i++)  
{ 
  var textBox = FindControl("AspTextBox" + i, false);
  if(textBox != null)
  {
    textBox.Text = codeBehindVariable[i];  
  }
}
JG in SD
  • 5,427
  • 3
  • 34
  • 46
-1

you can do something like this...

    int i = 0;
    foreach (Control ctrl in this.Controls)
    {
        if (ctrl is TextBox)
        {
            TextBox tempTextBox = (TextBox)ctrl;
            tempTextBox.Text = codeBehindVariable[i];
            i++;
        }
    }
udidu
  • 8,269
  • 6
  • 48
  • 68
  • You will still need to check the name of the control if it is a TextBox to see if it is AspTextBox0, AspTextBox1, etc... you should not rely on the control order in Controls – JG in SD Oct 16 '12 at 20:16