c# - 如何在 For 循环中创建标签

标签 c#

private ArrayList label= new ArrayList(30);

Label label_class = new Label();
Random r = new Random();

for (int i = 0; i < label.Count; i++) {
    ((Label)label[i]).Location = new Point(r.Next(ClientRectangle.Right -10),
                                           r.Next(ClientRectangle.Bottom - 10));
    ((Label)label[i]).Text = "o";
    ((Label)label[i]).Click += new EventHandler(Form1_Load);

    this.Controls.Add((Label)label[i]);

    ((Label)label[i]).Show();
}

这个 for 循环在 Form1_Load 中,因此它会在加载表单时运行。 问题是,当我断点时,我看到 forloop 内的代码没有被断点注意到/不运行。这是为什么??以及如何创建随机放置在 form1(window form)

上的多个标签

最佳答案

问题在

private ArrayList label= new ArrayList(30);

这会创建一个 ArrayList大小为 30,而不是具有 30 个元素的大小。

如果你做类似的事情

List<Label> labels = new List<Label>();

for (int i = 0; i < 30; i++) {
    var temp = new Label();

    temp.Location = new Point(r.Next(ClientRectangle.Right -10),
                                       r.Next(ClientRectangle.Bottom - 10));
    temp.Text = "o";
    temp.Click += new EventHandler(Form1_Load);

    temp.BackColor = System.Drawing.Color.White;

    this.Controls.Add(temp);

    temp.Show();
    labels.Add(temp) 
}

它应该可以工作。

此外,请注意我对 List<Label> 的使用而不是 ArrayList在某些情况下,您可能希望能够指定要取出的对象,但通常(在这种情况下)指定类型的通用形式会确保您做得更好。您不需要做所有您正在做的装箱,并且您将编写更少的代码行,所有这些都将更具可读性。

关于c# - 如何在 For 循环中创建标签,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7170673/

相关文章:

c# - C#中如何在两个字符串中查找相似的单词

c# - 当对象包含列表时覆盖相等成员

c# - 如何从 C# 中的 ListView 写入 XML 文件

c# - 如何调试由 vb6/vba 应用程序调用的 vs 2008 c# express dll?

c# - 创建使用一个 foreach 而不是多个的方法

C# 解析 JSON 问题

c# - Code First Entity Framework 在哪里保存数据

c# - 具有负载平衡的高负载服务器,使用 WCF 和 MSMQ

c# - 无法将文件上传到 Azure 存储 C#?

c# - 错误 "Missing operand after ' 类农算子”—— 'Bannon' 算子是什么?