Reputation: 87
I want to clear all controls specially textbox nad combobox. and I am using the following control to clear all fields.
private void ResetFields()
{
foreach (Control ctrl in this.Controls)
{
if (ctrl is TextBox)
{
TextBox tb = (TextBox)ctrl;
if (tb != null)
{
tb.Text = string.Empty;
}
}
else if (ctrl is ComboBox)
{
ComboBox dd = (ComboBox)ctrl;
if (dd != null)
{
dd.Text = string.Empty;
dd.SelectedIndex = -1;
}
}
}
}
The above code is not working properly in group box. In group box I have combo box and text box as well. Combo box shows the selected index = 1 of the group box. I also want to clear these controls as well. Any suggestions ????
Upvotes: 3
Views: 7024
Reputation: 7082
For TextBox
and ComboBox
public static void ClearSpace(Control control)
{
foreach (Control c in control.Controls)
{
var textBox = c as TextBox;
var comboBox = c as ComboBox;
if (textBox != null)
(textBox).Clear();
if (comboBox != null)
comboBox.SelectedIndex = -1;
if (c.HasChildren)
ClearSpace(c);
}
}
Usage:
ClearSpace(this); //Control
Upvotes: 10