简体   繁体   English

在C#中绘制标签数组

[英]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. 我不想使用Visual Studio拖放标签来绘制我需要的220,所以我决定创建一个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. 我在Form1_Load方法中使用此代码,但问题是它不会引发错误,但实际上并没有在Form上获取标签,它只是初始化标签但不绘制标签,有人知道如何实际将它们添加到表单。

This is really easy to do! 这真的很容易做到!

In your innermost for loop, add this line: 在最里面的for循环中,添加以下行:

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 . 但是,我建议您将标签添加到Panel ,这仅仅是因为自创建网格以来,您可能应该使用Panel将标签分组在一起。

Create a panel in the designer, call it labelPanel or whatever, and call this method instead in the innermost for loop: 在设计器中创建一个面板,将其labelPanel或其他名称,然后在最里面的for循环中调用此方法:

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. 例如,在您的表单中放置一个groupbox并将其命名为group1。 now add Labels to that group. 现在将标签添加到该组。 group1.Controls.Add(Tiles[i]); group1.Controls.Add(Tiles [i]);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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