How can I use a Foreach Statement to do something to my TextBoxes?
foreach (Control X in this.Controls)
{
Check if the controls is a TextBox, if it is delete it's .Text letters.
}
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)) {
..
}
You're looking for
foreach (Control x in this.Controls)
{
if (x is TextBox)
{
((TextBox)x).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 love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With