简体   繁体   English

TableLayoutPanel(C#WinForms)中的Foreach控件循环

[英]Foreach Loop of Controls in TableLayoutPanel (C# WinForms)

I have a TableLayoutPanel with 16 cells, and a label in each (representing times). 我有一个包含16个单元格的TableLayoutPanel,每个单元格中都有一个标签(表示时间)。

I am trying to use a foreach loop to add the times from a list to all the labels. 我正在尝试使用foreach循环将列表中的时间添加到所有标签。

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? 我想知道是否有面板或标签的属性来控制它们在foreach循环中的访问顺序? It is probably a simple solution, but I just can't find it! 这可能是一个简单的解决方案,但是我找不到它!

Thank you very much for the help! 非常感谢你的帮助!

Fix up your for loop for speed and clarity, for each loops can have weird occurrences with collections unless you cache it first. 修正您的for循环以提高速度和清晰度,因为每个循环在集合中都会出现怪异的现象,除非您先对其进行缓存。

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. 它的确取决于您在第一种情况下如何添加控件,您可能想看看您的获胜表单代码并查看名称/ ID,还可以给每个控件一个标签,然后在LessonsDAL.times下有一个字典,将使用标签名称并输出文本。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM