简体   繁体   中英

Drawing a label array in c#

For my project I would need to create clickable tiles sort of like a grid. To do so I have decided to try using an array of labels and clicking on any one of them would cause a mouse click event corresponding to the label clicked. I don't want to use the Visual Studio drag and drop labels to draw the 220 I need so i decided to create an array of Labels. Here is the code I am using to test out the use of the array of labels:

Label[] Tiles = new Label[10];
for (int i = 0; i != 10; i++)
{
    for (int n = 0; n != 22; n++)
    {
        Tiles[i] = new Label();
        Tiles[i].Size = new Size(62, 62);
        Tiles[i].Location = new System.Drawing.Point(n * 62 + 118, 106 + i * 62);
        Tiles[i].Text = (i+n).ToString();
        Tiles[i].Name = (i + n).ToString();
        Tiles[i].AutoSize = true;
        Tiles[i].Click += new System.EventHandler(this.label1_Click);
    }
}

I am using this code In the Form1_Load method but the problem is that it doesn't throw an error but also does not actually get the labels on the Form, it just initializes the labels but does not draw them, does someone know how to actually add them to the Form.

This is really easy to do!

In your innermost for loop, add this line:

this.Controls.Add(Tiles[i]);

It first gets all the controls on the form, then add the label in it!

However, I would advise you to add the labels to a Panel , just because since you're creating a grid, you should probably group the labels together using a Panel .

Create a panel in the designer, call it labelPanel or whatever, and call this method instead in the innermost for loop:

this.labelPanel.Controls.Add(Tiles[i]);

Please note that since the position of the labels are now relative to the panel, you need to adjust them again.

You have to add that labels to the form. like, put one groupbox in your form and named it as group1. now add Labels to that group. group1.Controls.Add(Tiles[i]);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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