djb
djb

Reputation: 17

Foreach Loop of Controls in TableLayoutPanel (C# WinForms)

I have a TableLayoutPanel with 16 cells, and a label in each (representing times).

I am trying to use a foreach loop to add the times from a list to all the labels.

int i = 0;
foreach (Control ctrl in tableLayoutPanel1.Controls)
{
    if (ctrl is Label)
    {
        ctrl.Text = LessonsDAL.times[i];
    }
    i++;
}

Although the text is being added to the labels, the loop seems to be adding the text to the labels in a random order. I am wondering if there are properties of the panel or the labels that would control the order they are being accessed in the foreach loop? It is probably a simple solution, but I just can't find it!

Thank you very much for the help!

Upvotes: 1

Views: 9293

Answers (1)

Braedon Wooding
Braedon Wooding

Reputation: 171

Fix up your for loop for speed and clarity, for each loops can have weird occurrences with collections unless you cache it first.

TableLayoutControlCollection controls = tableLayoutPanel1.Controls;

for (int i = 0; i < controls.Count; i++) {
    if (controls[i] is Label) {
        controls[i].Text = LessonsDAL.times[i];
    }
}

It does depend on how you added the controls in the first case, you may want to have a look at your win form code and see the names/ids, you could also give each control a label then have a dictionary under LessonsDAL.times that would take the label name and output the text.

Upvotes: 2

Related Questions