Adrian Brown Adrian Brown - 4 years ago 145
C# Question

Loop through labels and change values c#

I am looking to update some label text from an XML document.

The labels are named

supName1
,
supName2
etc.

I have a for loop which runs through for all the XML nodes in List.Count.

var n = list.Count;
for (int i = 0; i < n; i++)


I need to update the label text for each of the list.count but I can't figure out how to reference the labels.

From my VBA experience it would be something like
"supName"+i
but I can't figure it out for C#.

I've tried the following;

var label = (Label)Controls["supName" + i];


but it is returning null when trying to use it as follows;

label.Text = list[i].Attributes["name"].Value;

Answer Source

You need to find the labels in your form by their Name property, but have to keep in mind that they may be placed on a child control, not the form itself. The method that helps you here is ControlCollection.Find() that you can call on your form's Controls property which represents the form's ControlCollection:

int n = list.Count;
for(int i=0; i<n; i++)
{
    // the second argument "true" indicates to 
    // search child controls recursivly
    Label label = Controls.Find($"supName{i}", true).OfType<Label>().FirstOrDefault(); 
    if (label == null) continue; // no such label, add error handling
    label.Text = list[i].Attributes["name"].Value;
}
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download