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!
"The name 'text' does not exist in the current context".
text[i].Text you can only do this if
text
type implementsIEnumerable
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";
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With