Hey, I have a script with a button that creates some input with two labels:
C#
private void button1_Click_1(object sender, EventArgs e)
{
int countWorkers = Int32.Parse(checkedListBox1.Items.Count.ToString());
int countMissions = Int32.Parse(checkedListBox2.Items.Count.ToString());
int minBtw;
selectedWorkes = new string[countWorkers];
selectedMissions = new string[countMissions];
randomMissions = new string[countMissions];
if (countWorkers < countMissions)
minBtw = countWorkers;
else
minBtw = countMissions;
minBtw = addSelected(countWorkers, countMissions);
// addLabel(10, b, 40, 180);
for (int i = 0; i < minBtw; i++)
{
addLabel(i, selectedMissions[i], 40, 250 + 20 * i);
addLabel(i, selectedWorkes[i], 170, 250 + 20 * i);
}
}the label looks like this:
C#
private void addLabel(int i, String lblType, int x, int y)
{
Label l = new Label();
l.AutoSize = true;
l.Location = new System.Drawing.Point(x, y);
l.Name = "" + lblType + i;
l.Size = new System.Drawing.Size(146, 117);
l.TabIndex = 3;
l.Text ="" + lblType;
l.Font = new Font("Calibri", 12);
l.BorderStyle = BorderStyle.Fixed3D;
l.ForeColor = Color.Red;
l.BackColor = Color.White;
this.Controls.Add(l);
}
now I would like to create a second button to clear the dynamic label input.
how can I do it?

Rajanikant HawaldarRank #110 · 20.2K reputationPosted Jan 22, 2023, 9:17 AM EST
use this.Controls.Remove or this.Controls.RemoveAt
Amit MohantyRank #112 · 20K reputationPosted Jan 23, 2023, 12:03 AM EST
Create a ClearLabel method to clear all label
public void ClearLabel(Control control) { if (control is Label) { Label label = (Label)control; //if you want to clear the text only label.Text = String.Empty; //if you want to remove the label this.Controls.Remove(label); } else foreach (Control child in control.Controls) { ClearLabel(child); } }Then you can use it as in button click
ClearLabel(this);