-2

On my form I have a label with Name = "PART1".

In that label Text = "Company A".

What is the right way to get the result "Company A" by referring to the label using the string "PART1".

There are many labels on the form and I want to collect what has been entered in each label using:

for ( i = 1; i <= 100; i++ ) 
{
    result = GetTheValue("PART" + i.ToString());
}
Peter Duniho
  • 68,759
  • 7
  • 102
  • 136
Oscar
  • 7
  • 2

1 Answers1

2

Something like this should work

private string GetTheValue(string name)
{
    return this.Controls.OfType<Label>().FirstOrDefault(l => l.Name == name)?.Text;
}

Note that this is the Form which holds the labels. If your labels are placed in some container (like a Panel) you need to replace this with the corresponding container (e.g. panel1)

Jack T. Spades
  • 986
  • 6
  • 9