0

How can I dynamically update the text of labels in a form so their text is numbered, in order, from 1 to 25?

In pseudo code, something like this:

for (int i = 1; i <= 25; i++) {
    label + 'i'.Text = "i";
}
Ricky Smith
  • 2,379
  • 1
  • 13
  • 29

2 Answers2

1

I would do like this (tested):

foreach (var label in Controls.OfType<Label>())
{
    label.Text = label.Name.Replace("label", "");
}

Since you don't need to fill all label text in order, you can just loop through them and replace the "label" text. The assumptions are those you made, i.e. all labels are named "label1", "label2" etc., plus the fact that all labels are inside a common control (a panel) or the window itself, which is what I did.


EDIT: ADDITIONAL IDEAS

The solution above works but, to make things more interesting, you might add a method to prevent dealing with labels that do not respect your naming convention (i.e. "label" followed by a number):

foreach (var label in Controls.OfType<Label>())
{
    if (RespectsNamingConvention(label.Name))
    {
        label.Text = label.Name.Replace("label", "");
    }
}

where you have

private bool RespectsNamingConvention(string name)
{
    var Suffix = name.Replace("label", "");
    return 
        name.StartsWith("label") &&
        Suffix.Count() > 0 &&
        Suffix.Where(e => !Char.IsDigit(e)).Count() == 0;
}

i.e. you check whether your label name starts with "label", is followed by something, which contains just digits.

Another improvement could be getting all labels in your window, even if they're not in the same control.

Which can be done like shown in this question.

Francesco B.
  • 2,729
  • 4
  • 25
  • 37
  • @GrantWinney thank you. Perhaps my first answer was too concise, or maybe the downvoter wanted to "punish" an answer to a question he didn't deem worth. Best regards. – Francesco B. May 11 '18 at 20:33
0

Getting members of a class dynamically requires reflection. Something like this should do what you want. You will need to adjust it based on how the fields are declared.

for (int i = 0; i < 8; i++)
{
    var property = this.GetType().GetProperty("label" + i);
    var label = (Label)property.GetValue(this);
    label.Text = "Label " + i;
}
Ryan S
  • 521
  • 2
  • 6
  • 2
    *"Getting members of a class dynamically requires reflection."* No, it does not. Every control you add to a Windows Form is available in the `.Controls` collection, and is indexable by name, so you can replace all your reflection code with `var label = Controls["label" + i];` – Ron Beyer May 11 '18 at 20:35
  • In this case, yes, you are correct. However, generally you would need to use reflection to get a member in this way. – Ryan S May 11 '18 at 21:24