Problem while populating textboxes
-
Hi, I have five textboxes, where each of them defined as txtControl1 to txtControl5. Now I am running a loop to populate these textboxes with some text like this for (i=1; i<6; i++) { txtControl+i.Text = "Hello World" ; } Now when I am compiling, I am getting error "unable to find txtControl", with error message its clear the above line is unable to contact the control with the value of i. Is anyone know how to do that :confused: The Phantom.
-
Hi, I have five textboxes, where each of them defined as txtControl1 to txtControl5. Now I am running a loop to populate these textboxes with some text like this for (i=1; i<6; i++) { txtControl+i.Text = "Hello World" ; } Now when I am compiling, I am getting error "unable to find txtControl", with error message its clear the above line is unable to contact the control with the value of i. Is anyone know how to do that :confused: The Phantom.
This kind of loop can only be made if you store your textboxes previously in an ArrayList or normal array:
private TextBox[] myTextBoxes;
//only needed first time and then store it in a member variable
//e.g. in the constructor
myTextBoxes = new TextBox[] { txtControl1, txtControl2, txtControl3, txtControl4, txtControl5, txtControl6 };//now you can loop like this
for (i=1; i<6; i++)
{
myTextBoxes[i].Text = "Hello World" ;
} -
Hi, I have five textboxes, where each of them defined as txtControl1 to txtControl5. Now I am running a loop to populate these textboxes with some text like this for (i=1; i<6; i++) { txtControl+i.Text = "Hello World" ; } Now when I am compiling, I am getting error "unable to find txtControl", with error message its clear the above line is unable to contact the control with the value of i. Is anyone know how to do that :confused: The Phantom.
You will not be able to convert i (which is int variable) to first a string variable, and then a string variable to a textbox. Better way to do so is to declare an ArrayList (say called arrayTextBoxes). Then, initialize this ArrayList in the constructor of the form on which the textboxes are placed. You can declare the initial capacity of this ArrayList (which defaults to 16). Thereafter, (in the constructor of the form itself) populate the ArrayList with the instances of the 5 textboxes being used by you, by using the Add or AddRange method. Now you are ready to use the members (i.e., the textboxes)of the ArrayList in your code as, for example,- for (i=0; i<5; i++) { //here the arrayList is 0-based, so use i = 0 onwards ((TextBox) arrayTextBoxes[i]).Text = "Hello World" ; //arrayTextBoxes is the aforesaid ArrayList instance } In the aforesaid example, arrayTextBoxes[0] will represent the textbox1, and so on.