We often have to write a function to clear the content of a form on submit button-click. But the same thing can be done reusing the few lines of code in other parts of the project and overloading it to add more and more functionalities.
public static void ClearTextAndSelection(this Form frm) { foreach (Control ctrl in frm.Controls) { if (ctrl.GetType() == typeof(TextBox)) ((TextBox)ctrl).Text = string.Empty; else if (ctrl.GetType() == typeof(ComboBox)) ((ComboBox)ctrl).SelectedIndex = 0; else if (ctrl.GetType() == typeof(DateTimePicker)) ((DateTimePicker)ctrl).Value = DateTime.Now; else if (ctrl.GetType() == typeof(DataGridView)) ((DataGridView)ctrl).ClearSelection(); else if (ctrl.GetType() == typeof(GroupBox)) ((GroupBox)ctrl).ClearTextAndSelection(); else if (ctrl.GetType() == typeof(Panel)) ((Panel)ctrl).ClearTextAndSelection(); // An overload to clear controls contained in a panel } }
Please note that this function should be contained in a Static Class to make it usable from other parts of the project.
How to use it ?
Suppose I am working on button-click event. After saving all data into database, I want to reset the controls of a form to its initial state. I will simply call above function.
private void button1_Click(object sender, eventargs e) { this.ClearTextAndSelection(); // here I called that function. }
The function clears the form values including controls on child control suchs as the Panel.