Switch does not enter the cases

JDSolisV 20 Reputation points
2023-07-24T14:36:35.1133333+00:00

Hello there,

I am working with C# in Windows Forms. I have my parent form and inside it I open my child forms.

In my child forms I added a control tab, with different controls, all this in my presentation layer.
In the services layer I have a helper class with a reusable method to clean the controls of my forms.

This is my class to clean up the controls:

public static class Helper
    {
        public static void ClearFormControls(this Form form)
        {
            foreach(var control in form.Controls)
            {
                switch (control)
                {
                    case TextBox textbox: textbox.Text = string.Empty;break;
                    case TextBoxBase txt: txt.Text = string.Empty;break;
                    case ComboBox comboBox: comboBox.Text = String.Empty; break;
                    case CheckBox checkBox: checkBox.Checked = false; break;
                    case RadioButton radioButton: radioButton.Checked = false; break;
                    case DateTimePicker dateTimePicker: dateTimePicker.Value = DateTime.Now;break;
                    }
            }
        }
}

And called the class from my form:

private void Button1_Click(object sender, EventArgs e)
        {
            this.ClearFormControls();
        }

But the Switch does not enter the cases, It just ignores it, can anyone help me see where my mistake is?

I appreciate any help you can give me.

Thank you

DS

Windows Forms
Windows Forms
A set of .NET Framework managed libraries for developing graphical user interfaces.
1,873 questions
C#
C#
An object-oriented and type-safe programming language that has its roots in the C family of languages and includes support for component-oriented programming.
10,650 questions
0 comments No comments
{count} votes

Accepted answer
  1. Viorel 114.7K Reputation points
    2023-07-24T14:55:35.73+00:00

    Try another function:

    public static void ClearChildControls( this Control parentControl )
    {
        foreach( Control control in parentControl.Controls )
        {
            switch( control )
            {
            case TextBox textbox: textbox.Text = string.Empty; break;
            case TextBoxBase txt: txt.Text = string.Empty; break;
            case ComboBox comboBox: comboBox.Text = String.Empty; break;
            case CheckBox checkBox: checkBox.Checked = false; break;
            case RadioButton radioButton: radioButton.Checked = false; break;
            case DateTimePicker dateTimePicker: dateTimePicker.Value = DateTime.Now; break;
            default: control.ClearChildControls( ); break;
            }
        }
    }
    
    
    1 person found this answer helpful.

0 additional answers

Sort by: Most helpful