如何引用flowLayoutPanel中的Label?
How to refer to the Label in flowLayoutPanel?
如何修改 FlowLayoutPanel 中动态添加的元素?
我创建标签并将其添加到面板。
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);
}
我想单击 FlowLayoutPanel 中的任何标签并将字体更改为粗体,但我该怎么做?如何引用特定元素
为动态创建的标签添加一个Click
事件,并在for loop
中为每个动态标签创建一个新实例。
请阅读代码中的注释:
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);
}
如何修改 FlowLayoutPanel 中动态添加的元素? 我创建标签并将其添加到面板。
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);
}
我想单击 FlowLayoutPanel 中的任何标签并将字体更改为粗体,但我该怎么做?如何引用特定元素
为动态创建的标签添加一个Click
事件,并在for loop
中为每个动态标签创建一个新实例。
请阅读代码中的注释:
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);
}