扫雷游戏。使用循环创建标签

本富兰

新成员
已加入
2021年1月2日
留言内容
1
编程经验
Beginner
你好

我正在尝试创建400个标签来填充扫雷项目的控制面板。我正在使用for循环创建它,但似乎出错了。这是我到目前为止所拥有的。

C#:
int distance = 10;
int labcounter = 0;

private void GreyPanel_Paint(object sender, PaintEventArgs e)
{
    new List<Label> { label1, label2,};

    while ( labcounter <= 400)
    {
        Label lbl = new Label();

        this.Controls.Add(lbl);

        lbl.BackColor = System.Drawing.Color.SkyBlue;
        lbl.Location = new System.Drawing.Point(10 + distance, 10 + distance);
        lbl.Name = "label1" + labcounter;
        lbl.Size = new System.Drawing.Size(20, 20);
        lbl.TabIndex = 0;

        labcounter = labcounter + 1;


另外,还有什么方法可以将其添加到designer.cs文件中,以便在加载表单时所有400个标签都已填充到控制面板中。
任何援助将不胜感激。

谢谢
 
由主持人最后编辑:

金西尼

C#论坛主持人
工作人员
已加入
2011年4月23日
留言内容
3,501
地点
悉尼,澳大利亚
编程经验
10+
Lots to address here. Firstly, Paint could not be a more wrong event to put that code in. Your Panel will get painted numerous times and obviously you don't want to create 400 Labels every time. The Paint event is only for drawing on a control using GDI+, which you're not doing. That said, using 400 control may well be a bad idea so using GDI+ instead may well be a better idea. You'll know if your form seems to be sluggish, although Labels won't be as bad as more complex controls.

Next, if you want to do something once before the form load then you do it in the Load event handler. The clue is in the name.

If you are going to use controls in a grid layout like this then you'd make your life easier by using the control designed specifically for that, i.e. the TableLayoutPanel. Add one to your form and set up the rows and columns and then you can just add Labels to it without having to worry about their 地点. I'd also recommend setting the Dock property to Fill and then they will automatically fill the cell they're in. You will have already made sure that the cells are the exact size you want the Labels to be. You won't have to pointlessly set the Name because you can access each child by row and column index from the parent.
 
最佳 底部