private void CleanForm()
{
foreach (var c in this.Controls)
{
if (c is TextBox)
{
((TextBox)c).Text = String.Empty;
}
Try this:
var t = this.Controls.OfType<TextBox>().AsEnumerable<TextBox>();
foreach (TextBox item in t)
{
item.Text = "";
}
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);
}
}
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 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!
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);
}