简体   繁体   English

flowLayoutPanel中如何参考Label?

[英]How to refer to the Label in flowLayoutPanel?

How can I modify dynamically added elements in FlowLayoutPanel?如何修改 FlowLayoutPanel 中动态添加的元素? I create the label and add it to the panel.我创建了 label 并将其添加到面板中。

Random randNumbers = new Random();
        int amountOfNumbers = randNumbers.Next(5, 10);

        var table = flowLayoutPanel1; Label element;

        for (int i = 0; i < amountOfNumbers; i++)
        {
            int valueOfNumbers = randNumbers.Next(-101, 100);
            element = new Label();
            element.Font = new Font("Tobota", 13, FontStyle.Regular);
            element.Text = valueOfNumbers.ToString();
            table.Controls.Add(element);
        }

I want to click on any label in FlowLayoutPanel and change the font to bold, but how can I do that?我想点击 FlowLayoutPanel 中的任何 label 并将字体更改为粗体,但我该怎么做呢? How to refer to a specific element如何引用特定元素

Add a Click event to the dynamically created labels, and create a new instance of each dynamic label inside the for loop .Click事件添加到动态创建的标签中,并在for loop中创建每个动态 label 的新实例。
Please read comments inside the code:请阅读代码中的注释:

private void Example()
{
    Random randNumbers = new Random();
    int amountOfNumbers = randNumbers.Next(5, 10);

    for (int i = 0; i < amountOfNumbers; i++)
    {
        int valueOfNumbers = randNumbers.Next(-101, 100);
        Label element = new Label();
        element.Font = new Font("Tobota", 13, FontStyle.Regular);
        element.Text = valueOfNumbers.ToString();
        // Set an name, you may want to use it
        element.Name = "lbl_" + i.ToString();
        // Add a click event
        element.Click += OnLabelClicked;
        table.Controls.Add(element);
    }

}

private void OnLabelClicked(object sender, EventArgs e)
{
    // Cast the object to the clicked label
    Label clickedLabel = (Label)sender;
    // Here you can also check the name of the label if you need
    MessageBox.Show(clickedLabel.Name);
    // Make the font of the clicked label bold
    clickedLabel.Font = new Font(clickedLabel.Font.FontFamily, clickedLabel.Font.Size, FontStyle.Bold);
}

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

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