【问题标题】:Putting labels in an array using for loop in Visual Studio C#在 Visual Studio C# 中使用 for 循环将标签放入数组中
【发布时间】:2014-05-27 06:19:04
【问题描述】:

我想在表单加载时将标签放在一个数组中,但我不想一个一个地对它们进行编码,我想使用一个 for 循环,但我不知道这在 C# 中是如何工作的。

我的代码:

Dates[0] = this.labelrect0; 
Dates[1] = this.labelrect1;
Dates[2] = this.labelrect2;
Dates[3] = this.labelrect3;

我想做什么:

for(int n = 0; int > array.Count; c++)
{
 Dates[n] = this.labelrect+n;  //how do i concatenate n to labelrect?
}

【问题讨论】:

  • 一种非直接的方式可能是将标签放在Label[] labelrect 数组中并通过labelrect[n] 寻址它们。然后Dates[n] = this.labelrect[n]循环。

标签: c# winforms for-loop


【解决方案1】:

如果DatesLabel[],你可以试试这个:

for(int n = 0; n < array.Count; n++)
{
 Dates[n] =(Label) Controls.Find("labelrect"+n, true)[0]; 
}

【讨论】:

  • 请问行尾的[0]是做什么的?
  • @Sai: Control.Find() 方法返回与给定名称匹配的控件数组,因此我们应该考虑数组中的第一项。
  • 我明白了。哦,顺便说一句,Controls.Find 询问 2 个参数,所以我使用了 Controls.Find("labelrect"+n, true) 因为第二个参数是一个布尔值,它询问我是否要搜索子控件。无论如何,我得到了它的工作。谢谢!
  • @Sai:是的,你是对的,会有两个参数,我更新了我的帖子。很高兴能得到你的帮助。
【解决方案2】:

您可以使用Controls 属性。如果您有一个包含这些标签的Container 控件,那么您可以使用&lt;ContainerID&gt;.Controls 获取控件中包含的控件集合。

【讨论】:

    【解决方案3】:

    我通常会将标签的索引放在标签属性中,然后我会使用标签遍历控件集合以将控件分配给正确的索引。像这样的。

    for (int i = 0; i < Controls.Count; i++)
    {
        if(Controls[i] is Label)
            Dates[int.Parse(Controls[i].Tag.ToString())] = (Label)Controls[i];
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-11-25
      • 1970-01-01
      • 2023-03-31
      • 1970-01-01
      • 2014-08-27
      相关资源
      最近更新 更多