After looking at the code you posted in SAKryukov's answer, I can see that you are instantiating
newlabel and
newlabel2 each time the mouse is clicked. The problem is that these instantiations will not be pointed at the same controls that were added to the panel. Instead, they will be brand new label controls each time.
Option 1 - What you will need to do is specify the
Name
property of each label and then remove them using the
Name
:
private void panel2_MouseClick(object sender, MouseEventArgs e)
{
switch(e.Button)
{
case MouseButtons.Left:
Label newlabel = new Label();
newlabel.Name = "newlabel";
newlabel.Text = "0";
newlabel.Size = new Size(10, 15);
newlabel.BackColor = Color.Transaparent;
newlabel.Location = new Point(e.Location.X, 7);
panel2.Controls.Add(newlabel);
break;
case MouseButtons.Right:
Label newlabel2 = new Label();
newlabel2.Name = "newlabel2";
...
case MouseButtons.Middle:
panel2.Controls.RemoveByKey("newlabel");
panel2.Controls.RemoveByKey("newlabel2");
break;
}
}
Option 2 - You will need to instantiate the labels outside the event handler so that when you remove them, they will still be pointed at the ones that were added (this assumes you are only adding one of each). You will not need to specify the
Name
property:
Label newlabel, newlabel2;
private void panel2_MouseClick(object sender, MouseEventArgs e)
{
switch(e.Button)
{
case MouseButtons.Left:
newlabel = new Label();
newlabel.Text = "0";
newlabel.Size = new Size(10, 15);
newlabel.BackColor = Color.Transaparent;
newlabel.Location = new Point(e.Location.X, 7);
panel2.Controls.Add(newlabel);
break;
case MouseButtons.Right:
newlabel2 = new Label();
...
case MouseButtons.Middle:
panel2.Controls.Remove(newlabel);
panel2.Controls.Remove(newlabel2);
break;
}
}
Option 3 - Loop through the controls and remove all Label controls that have been added:
int counter = 1;
private void panel2_MouseClick(object sender, MouseEventArgs e)
{
switch(e.Button)
{
case MouseButtons.Left:
case MouseButtons.Right:
Label newlabel = new Label();
newlabel.Name = "newlabel" + counter.ToString();
newlabel.Text = "0";
newlabel.Size = new Size(10, 15);
newlabel.BackColor = Color.Transaparent;
newlabel.Location = new Point(e.Location.X, 7);
panel2.Controls.Add(newlabel);
counter++;
break;
case MouseButtons.Middle:
foreach(Control c in panel2.Controls)
{
if(c is Label)
{
panel2.Controls.Remove(c);
}
}
break;
}
}