I am drawing set of Labels dynamically and i want to remove them. I am using the same button to remove and add new Labels. The labels are drawn randomly with random coordinates. But, when i am pressing the button the old Labels should me removed and the new Labels appeared. But, what I am having is that the new labels appears and old Labels appears but empty labels. I want them to be remove at all. See the picture:
//Global Intialization
int xCoor;
int yCoor;
//send the random method
Random coor = new Random();
private void btnRun_Click(object sender, EventArgs e)
{
//Removing the Labels after drawing them in the picBox
this.RemoveOldLabels();
//to draw the Labels rendomely.
for (int x = 1; x <= 25; x++)
{
for (int i = 0; i < 1; i++)
{
//Get the Coordinates for X,Y
xCoor = coor.Next(0, 750);
yCoor = coor.Next(0, 500);
//Start Greating the Labels
Label nodeLabel1 = new Label();
nodeLabel1.Text = x + " : " + xCoor + "," + yCoor;
nodeLabel1.AutoSize = true;
nodeLabel1.Location = new Point(xCoor + 10, yCoor + 5);
nodeLabel1.ForeColor = System.Drawing.Color.Red;
nodeLabel1.BackColor = Color.LightBlue;
//Draw the Labels in the PicBox
this.picNodes.Controls.Add(nodeLabel1);
}
}
}
//this to remove the Labels
private void RemoveOldLabels()
{
List<Label> LabelsToRemove = new List<Label>();
foreach (var x in this.picNodes.Controls)
{
if (x.GetType() == typeof(System.Windows.Forms.Label))
{
LabelsToRemove.Add((Label)x);
}
}