1

This is my code that helps me create a button after I click another button. I need help so that when I click another button, let's say button Remove it will remove the last button I created.

private void BtnShto_Click(object sender, EventArgs e)
{
    Button button = new Button();
    button.Parent = this.pnlMenu;
    button.Location = new Point(12 + rreshta, 16 + kolona);
    button.Size = new Size(92, 84);
    button.FlatStyle = FlatStyle.Flat;
    button.BackColor = Color.White;
    button.Text = "Tavolina " + j;
    button.Name = "btnTavolina" + j;
    j++;
    rreshta += 100;
    if(rreshta > 500)
    {
        kolona += 100;
        rreshta = 0;
    }
}
Milo
  • 3,365
  • 9
  • 30
  • 44

1 Answers1

0

If you are looking to remove the last button added (then the button before that, and so on), in response to a button click, you need to track the items you've added. I would suggest that you add the push the new button to a Stack, defined outside of your click handler, then pop them off when removing.

Add the stack to the form

var addedButtons = new Stack<Button>();

In BtnShto_Click, add new buttons to the stack.

this.addedButtons.Push(button);

In the Click handler of the remove button, remove the items and dispose of them:

if (this.addedButtons.Count > 0)
{
    Button toRemove = this.addedButtons.Pop();
    this.pnlMenu.Contorls.Remove(toRemove);
    toRemove.Dispose();
}
Graham
  • 609
  • 6
  • 9