Clearing a form

Using VS2005

Can anyone help in making this code more generic

private void fnClear(Control _parent)

{

//for all the controls on the tabcontrol

foreach (Control _ctl in _parent.Controls)

{

if (_ctl.HasChildren)

{

foreach (Control _child1 in _ctl.Controls)

{

if (_child1.HasChildren)

{

foreach (Control _child2 in _child1.Controls)

{

//do the tab control

if (_child2.GetType() == typeof(TextBox))

((TextBox)_child2).Clear();

if (_child2.GetType() == typeof(ComboBox))

((ComboBox)_child2).SelectedIndex = -1;

if (_child2.GetType() == typeof(MaskedTextBox))

((MaskedTextBox)_child2).Clear();

if (_child2.GetType() == typeof(DateTimePicker))

((DateTimePicker)_child2).Text = "";

}

}

}

}

}

}



Answer this question

Clearing a form

  • Lightening

    Could you please give me an example - I am somewhat new..
  • WelshBird

    Setup a generic list(s) containing the controls you want to clear at the startup of the form. (Specific to to the types of clearing needed.)

    When the time comes to clear them, enumerate through the list(s).

    If it has to be dynamic, then doing this method will only have the containers enumerated once, the penalty paid at startup and not for every clear.


  • Martin Masse


    private void ClearControl(Control control)
    {
        if (control is TextBoxBase)
            (control as TextBoxBase).Clear();
        if (control is ComboBox)
            (control as ComboBox).SelectedIndex = -1;
        if (control is DateTimePicker)
            (control is DateTimePicker).Text = string.Empty;
        foreach(Control child in control.Controls)
            ClearControl(child);
    }

     



  • Clearing a form