Foreach Control in form, how can I do something to all the TextBoxes in my Form?
You're looking for
foreach (Control x in this.Controls)
{
if (x is TextBox)
{
((TextBox)x).Text = String.Empty;
}
}
Also you can use LINQ. For example for clear Textbox
text do something like:
this.Controls.OfType<TextBox>().ToList().ForEach(t => t.Text = string.Empty);
The trick here is that Controls
is not a List<>
or IEnumerable
but a ControlCollection
.
I recommend using an extension of Control that will return something more..queriyable ;)
public static IEnumerable<Control> All(this ControlCollection controls)
{
foreach (Control control in controls)
{
foreach (Control grandChild in control.Controls.All())
yield return grandChild;
yield return control;
}
}
Then you can do :
foreach(var textbox in this.Controls.All().OfType<TextBox>)
{
// Apply logic to the textbox here
}
If you are using C# 3.0 or higher you can do the following
foreach ( TextBox tb in this.Controls.OfType<TextBox>()) {
..
}
Without C# 3.0 you can do the following
foreach ( Control c in this.Controls ) {
TextBox tb = c as TextBox;
if ( null != tb ) {
...
}
}
Or even better, write OfType in C# 2.0.
public static IEnumerable<T> OfType<T>(IEnumerable e) where T : class {
foreach ( object cur in e ) {
T val = cur as T;
if ( val != null ) {
yield return val;
}
}
}
foreach ( TextBox tb in OfType<TextBox>(this.Controls)) {
..
}