0

I have five Labels in my form.

The names of the label are the following.

1) labelTeam1Name.Text
1) labelTeam2Name.Text
3) labelTeam3Name.Text
4) labelTeam4Name.Text
5) labelTeam5Name.Text

now I want to run a loop and get the text values of the label

for( int i = 1; i < 6; i++ )
{
    string str = labelTeam(i)Name.Text  // Get the values based on the input i

}

I can definitely fill these values in an array or list and then call them in the loop.

is it possible to do something like this labelTeam(i)Name.Text?

3 Answers 3

3

You can use Controls and OfType

Filters the elements of an IEnumerable based on a specified type.

var results = Controls.OfType<Label>().Select(x => x.Text);

or

foreach (var ctrl in Controls.OfType<Label>())
{
    //var str = ctrl.Text;    
}

if you need to base this on the name, you could use Find or

var labels = Controls.OfType<Label>().ToList();

for (int i = 0; i < labels.Count(); i++)
{
   var label = labels.FirstOrDefault(x => x.Name == $"blerp{i}derp");

   if (label != null)
   {

   }
} 
Sign up to request clarification or add additional context in comments.

Comments

2

You can use the Controls.Find() method:

for( int i = 1; i < 6; i++ )
{
    string str = ((Label)Controls.Find("labelTeam" + i + "Name",true)[0]).Text  // Get the values based on the input i

}

1 Comment

In that case, you can write $"labelTeam{i}Name", instead of "labelTeam" + i + "Name".
1

You can use a Label array.

System.Windows.Forms.Label[] Labels = new System.Windows.Forms.Label[5];

Labels[0] = labelTeam1Name;

Labels[1] = labelTeam2Name;

Labels[2] = labelTeam3Name;

Labels[3] = labelTeam4Name;

Labels[4] = labelTeam5Name;

for( int i = 0; i < Labels.Lenth; i++ )
{
    string str = Labels[i].Text; 
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.