FrustratedNewbie
FrustratedNewbie

Reputation: 33

How do you Loop through a specific Textboxes

I have found code that will allow me to loop through every textbox on a form and then allow me to compare it against some criteria. But thats not what i want to do. I know the 4 textboxes i want to loop through, i just don't know how to refer to those 4, without looping through every textbox on the form. Which from my program point of view isn't really an issue as i'll only have about 20 textboxes in total. But that isn't the point, i want to know how to do it propperly.

Basically i have 4 Textboxes : MyTxtBox1, MyTxtBox2, MyTxtBox3 and MyTxtBox4. And its only these i want to loop through.

Something along the lines of:

          for (int i = 1; i < 5; i++)
          {   
    string myName = "MyTxtBox" + i.ToString();
            if (MyFunction(this.myName))
            {
                return;
            }
          }

But this.myName doesn't work and thats probably because its just a string. I don't know how i can refer to the textbox on the form after i've built the textbox name as a string.

Can anyone see what it is i'm trying to do and is it even possible? Or will i have to loop through every textbox on the form and then test against its .Name property.

Thanks

Upvotes: 0

Views: 2332

Answers (4)

user729975
user729975

Reputation: 117

this.Controls["yourtextboxname" + Convert.ToString(i + 1)].Text;

Upvotes: 0

Khemka
Khemka

Reputation: 108

A textbox is a Control. Create a ControlCollection and then use the ControlCollection.Find()method... Something like

Control.ControlCollection collection = this.Controls;
Control newControl=collection.Find(<textbox name here>,true);

and run it thru the required loop.

Upvotes: 3

jonsca
jonsca

Reputation: 10381

Try placing them into a groupbox together, that way you can access all the controls of that groupbox.

Upvotes: 0

Jaapjan
Jaapjan

Reputation: 3385

Think about something along the lines of this:

{
    List<Textbox> list = new List<Textbox>();
    list.Add(myBox1);
    list.Add(myBox1);
    ..

    foreach (Textbox box in list)
        if (MyFuction(box))
            return;
}

Upvotes: 1

Related Questions