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.

1

3 Answers 3

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.

Sign up to request clarification or add additional context in comments.

Comments

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

Comments

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

1 Comment

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

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.