Reputation: 2268
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?
Upvotes: 0
Views: 76
Reputation: 81583
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)
{
}
}
Upvotes: 3
Reputation: 1175
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;
}
Upvotes: 1
Reputation: 106
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
}
Upvotes: 2