0

Im trying to delete all the buttons in my WinForm.But somehow, it keeps few buttons in the form. How can I remove all the buttons in my form?What is the mistake at my code?!

void ClearScreen()
    {
        foreach (Control c in this.Controls)
        {
            if (c is Button)
                this.Controls.Remove(c);

        }


    }
Noam650
  • 113
  • 1
  • 2
  • 8
  • Why you need to remove them? Can you provide more information? May be just hide/collapse them using binding and corresponding converter? Btw you just cycle thru children of current control, so you need to write recursive method and call it on every child – trimeyko May 28 '12 at 09:35
  • what? I am showing a sequence in this form. and I want to show a Different sequence when the user want. So I need to get rid from the buttons in my form, and activate new one's. – Noam650 May 28 '12 at 09:37
  • I tried your code and it is working. What is the error you get? – chaliasos May 28 '12 at 09:45
  • I don't get any error. It just do not remove all the buttons. – Noam650 May 28 '12 at 09:48
  • possible duplicate of [Find all controls in WPF Window by type](http://stackoverflow.com/questions/974598/find-all-controls-in-wpf-window-by-type) – V4Vendetta May 28 '12 at 09:48
  • Slap your controls on a frame and hide that. You don't want to remove all controls. – CodeCaster May 28 '12 at 09:52
  • @CodeCaster how do i do that? – Noam650 May 28 '12 at 09:57
  • @Noam650 For some reason it is not removing the last button. Check my answer, that worked for me. – chaliasos May 28 '12 at 10:01

3 Answers3

3

The reason your code doesn't work is that you are modifying a collection while you are using the enumerator to loop through it.

Emond
  • 50,210
  • 11
  • 84
  • 115
2

Try this:

void ClearScreen()
{
    List<Button> _buttons = this.Controls.OfType<Button>().ToList();

    foreach (var button in _buttons)
    {
        this.Controls.Remove(button);
    }
}
chaliasos
  • 9,659
  • 7
  • 50
  • 87
0
foreach (Button btn in this.Controls.OfType<Button>())
            {
                this.Controls.Remove(bbb);
            }

this is a generic way to remove all the buttons from a form

doneyjm
  • 145
  • 6