Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to iterate over windows forms controls [duplicate]

Tags:

c#

loops

winforms

I have 5 textboxes with 5 labels,named like this:

  • text1, text2, text3, etc.
  • label1, label2, label3, etc.

What I want to do is to target each of them and apply the same code, without having to write something individually. I was thinking about a loop like this:

for (int i = 1; i <= 5; i++)
{
    try
    {
        tcpCLient.ConnectAsync(text(i).Text, 80);
        label(i).Text = "Online";
    }
    catch (Exception)
    {
        label(i).Text = "Offline";
    }
}

The problem is that Visual Studio won't let me compile as "The name 'text' does not exist in the current context".

Is this the wrong approach? How would you do this?

Thank you very much!

like image 279
Goosfraba Avatar asked Jan 01 '23 06:01

Goosfraba


1 Answers

"The name 'text' does not exist in the current context".

text[i].Text you can only do this if text type implements IEnumerable

You can do this to enumerate over your controls

var labels = new List<Label> { label1, label2, label3};
var textBoxs = new List<TextBox> { text1, text2, text3};


for (int i = 1; i <= 5; i++)
{
    try
    {
        tcpCLient.ConnectAsync(textBoxs[i].Text, 80);
        labels[i].Text = "Online";
    }
    catch (Exception)
    {
        labels[i].Text = "Offline";
    }
}
like image 104
Clint Avatar answered Jan 02 '23 20:01

Clint