Try this:
var t = this.Controls.OfType<TextBox>().AsEnumerable<TextBox>();
foreach (TextBox item in t)
{
item.Text = "";
}
private void CleanForm(Control ctrl)
{
foreach (var c in ctrl.Controls)
{
if (c is TextBox)
{
((TextBox)c).Text = String.Empty;
}
if( c.Controls.Count > 0)
{
CleanForm(c);
}
}
}
When you initially call ClearForm, pass in this, or Page (I assume that is what 'this' is).
I like lambda :)
private void ClearTextBoxes()
{
Action<Control.ControlCollection> func = null;
func = (controls) =>
{
foreach (Control control in controls)
if (control is TextBox)
(control as TextBox).Clear();
else
func(control.Controls);
};
func(Controls);
}
Good luck!
Maybe you want more simple and short approach. This will clear all TextBoxes too. (Except TextBoxes inside Panel or GroupBox).
foreach (TextBox textBox in Controls.OfType<TextBox>())
textBox.Text = "";
I improved/fixed my extension method.
public static class ControlsExtensions
{
public static void ClearControls(this Control frm)
{
foreach (Control control in frm.Controls)
{
if (control is TextBox)
{
control.ResetText();
}
if (control.Controls.Count > 0)
{
control.ClearControls();
}
}
}
}
You can try this code
protected override bool ProcessCmdKey(ref Message msg, Keys keyData)
{
if(keyData==Keys.C)
{
RefreshControl();
return true;
}
return base.ProcessCmdKey(ref msg, keyData);
}
And this for clearing all controls in form like textbox, checkbox, radioButton
you can add different types you want..
private void ClearTextBoxes(Control control)
{
foreach (Control c in control.Controls)
{
if (c is TextBox)
{
((TextBox)c).Clear();
}
if (c.HasChildren)
{
ClearTextBoxes(c);
}
if (c is CheckBox)
{
((CheckBox)c).Checked = false;
}
if (c is RadioButton)
{
((RadioButton)c).Checked = false;
}
}
}
We had a problem like this some weeks before. If you set a breakpoint and have a deep look into this.Controls
, the problem reveals it's nature: you have to recurse through all child controls.
The code could look like this:
private void CleanForm()
{
traverseControlsAndSetTextEmpty(this);
}
private void traverseControlsAndSetTextEmpty(Control control)
{
foreach(var c in control.Controls)
{
if (c is TextBox) ((TextBox)c).Text = String.Empty;
traverseControlsAndSetTextEmpty(c);
}
}
Your textboxes are probably inside of panels or other containers, and not directly inside the form.
You need to recursively traverse the Controls
collection of every child control.
Source: Stackoverflow.com