C# - Clear a container of controls quickly.
I am almost ashamed to post such trivial code, but here is a little function that clears control values that are in a container control that you pass into it (like a groupbox or panel).
Code:
public void ClearControlValues(System.Windows.Forms.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(Label))
((Label)ctrl).Text = "";
if(ctrl.GetType() == typeof(DateTimePicker))
((DateTimePicker)ctrl).Text = "";
}
}
catch(Exception ex)
{
MessageBox.Show(ex.ToString());
}
}
You can add your own additions in there for other types of controls, I just translated this for someone else, and I didn't want to lose it because I know I may use this in the future.
So you would call it by passing in a groupbox or a panel that contains controls you want to clear the values of. If the container control contains controls that are not checked in this function, they are ignored.