# VBForums CodeBank > CodeBank - C# >  C# - Clear a container of controls quickly.

## hellswraith

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).


```
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.

----------


## Danial

There is slight problem with the above code, as it does not clear any conrols embeded within other container.

So adding extra two line and making it Recursive would fix it.

e.g



```
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 = "";

                         if(ctrl.Controls.Count>0)
                               ClearControlValues(ctrl);
		}
	}
	catch(Exception ex)
	{
		MessageBox.Show(ex.ToString());
	}
}
```

Just thougt some one else might find it useful, i use it quite a lot to clear my Form values.

----------


## hellswraith

Your right, thanks for adding that.  I normally don't have control containers within control containers, so I totally left that piece out.

----------

