samedi 26 janvier 2019

How to clear controls i.e. TextBoxes, ComboBoxes, CheckBoxes etc. inside a panel control in C#

I have a form with TextBoxes, ComboBoxes, CheckBoxes, DataGridView inside a panel. On a Button Click event I have the following procedure to clear the controls:

public void ClearControlValues(Control Container)
    {
        try
        {
            foreach (Control ctrl in Container.Controls)
            {
                if (ctrl.GetType() == typeof(TextBox))
                {
                    ((TextBox)ctrl).Text = "";
                }

                if (ctrl.GetType() == typeof(ComboBox))
                {
                    ((ComboBox)ctrl).SelectedIndex = -1;
                }

                if (ctrl.GetType() == typeof(CheckBox))
                {
                    ((CheckBox)ctrl).Checked = false;
                }

                if (ctrl.GetType() == typeof(DateTimePicker))
                {
                    ((DateTimePicker)ctrl).Text = "";
                }

                if (ctrl.GetType() == typeof(DataGrid))
                {
                    ((DateTimePicker)ctrl).Text = "";
                }

                if (ctrl.Controls.Count > 0)
                {
                    LockControlValues(ctrl);
                }

            }
        }
        catch (Exception ex)
        {
            MessageBox.Show(ex.ToString());
        }
    }

Button Click calling:

ClearControlValues(this);

But: Controls inside my panel "MainPanel" is not clearing. What do I am missing?




Aucun commentaire:

Enregistrer un commentaire