3
Reply

Cicle for auto assign TextBox to variables, how to do it?

Ricardo Cunha

Ricardo Cunha

Sep 15 2009 7:35 PM
2.9k
Hey, in class the teacher told us to do some programs, some of them with many TextBox and I tried hard to read the TextBoxes and save them onto a array inside a for, so that I didn't had to assign every single one of them manually, but in the end that was the result, a very stupid way of programming I think, I asked my teacher and even she could come up with a way of doing that...

All the textboxes are named "txt*" were * is 1, then 2, 3.... You get the idea, so I thought, well gonna save a string were it was "txt" + x(variable that is incremented) + ".Text"(Because if I don't put a real TextBox name it doesn't recognise it, if instead of putting txt1 I put txtx, txt(x), txt + x or other way in the end I couldn't put .Text, so I made that string) but without result, as it didn't accept the string.

For Example:
Instead of doing:

Vec[0] = Convert.ToInt32(txt1.Text);
Vec[1] = Convert.ToInt32(txt2.Text);
Vec[2] = Convert.ToInt32(txt3.Text);
Vec[3] = Convert.ToInt32(txt4.Text);
Vec[4] = Convert.ToInt32(txt5.Text);

I want some cicle that could do something like:
int x = 1;

for (int i = 0; i < 5; i++)
{
Vec[i] = Covert.ToInt32(txt(x).Text);
x++;
}

Or instead a way to convert a string to the TextBox name would be appreciated...

I couldn't find a way to do something like that, please help me...


Answers (3)