Control array type loop in C#/ASP.NET

2.7k Views Asked by At

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.

3

There are 3 best solutions below

1
On

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++;
        }
    }
0
On

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.

0
On

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];  
  }
}