Reputation: 13
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";
}
Upvotes: 0
Views: 452
Reputation: 3097
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.
Upvotes: 1
Reputation: 531
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;
}
Upvotes: 0