SomeNerdAtWork
SomeNerdAtWork

Reputation: 164

How can I clear all form controls of an MDI child?

I have a function that clears a non-MDI child form, but when I apply it to an MDI child it doesn't do anything. I've tried attacking this problem from a few different angles without any luck, was hoping stackoverflow could help!

I've tried the code shown, I've also attempted to reference the child of the parent of the current form (Which is circular I know).

    public static void ResetAllControls(Control form)
    {
        foreach (Control control in form.Controls)
        {
            if (control is TextBox)
            {
                TextBox textBox = (TextBox)control;
                textBox.Text = "";
            }

            if (control is ComboBox)
            {
                ComboBox comboBox = (ComboBox)control;
                if (comboBox.Items.Count > 0)
                    comboBox.SelectedIndex = 0;
            }

            if (control is CheckBox)
            {
                CheckBox checkBox = (CheckBox)control;
                checkBox.Checked = true;
            }

            if (control is ListBox)
            {
                ListBox listBox = (ListBox)control;
                listBox.ClearSelected();
            }
        }
    }

I expect that passing this would clear all form controls as it does with standard forms.

Upvotes: 0

Views: 446

Answers (1)

Adam Jachocki
Adam Jachocki

Reputation: 2125

I'm pretty sure that you have some kind of container on this for (eg. Panel) and controls are on this panel. Form.Controls will give you only controls that lay directly on the form. So you will have to do it recurrently:

public static void ResetAllControls(Control parent)
{
    foreach(var child in parent.Controls)
        ResetAllControls(child);

    if(parent is TextBox)
    {
        (parent as TextBox).Text = "";
        return;
    }
    //and so on
}

Upvotes: 1

Related Questions