Reputation: 3
How can I modify dynamically added elements in FlowLayoutPanel? I create the label and add it to the panel.
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? How to refer to a specific element
Upvotes: 0
Views: 213
Reputation: 5986
Add a Click
event to the dynamically created labels, and create a new instance of each dynamic label inside the for loop
.
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);
}
Upvotes: 0