Question Minesweeper game. using loops to create labels

BenFoulan

New member
Joined
Jan 2, 2021
Messages
1
Programming Experience
Beginner
Hi

I am trying to create 400 labels to fill my control panel for a minesweeper project. I am using a for loop to create it but seem to be going wrong. Here is what i have so far.

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;


Also is there any way I can add this to the designer.cs file in order that when the form loads all 400 labels have populated the control panel.
Any assistance would be appreciated.

Thanks
 
Last edited by a moderator:
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 Location. 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.
 
Back
Top Bottom