Home >
Main >
An Interesting Use of a C# Foreach Loop
An Interesting Use of a C# Foreach Loop
Posted in Blog by Tieson | geeksneversleep.com
Nov
4
2008
I've seen many different ways of clearing the contents of controls in a Windows Form object, some of which can be quite elaborate. While it can be fun to come up with these convoluted schemes, there is an easier way. Here's what I do...
I implement a foreach loop, and iterate over the form's collection of Controls, comparing each control to the Textbox control type, using the is keyword. This keyword, is, performs a type comparison. If the Control is the type I am comparing it to, then I perform a function call, in this case a call to the Control's ResetText() method.
The beauty of this chunk of code is that it scales with the form itself. If the form has 3 controls or 300, the same code can be applied without modification.
Pretty sweet, huh? Here's the code (written for C#):
foreach(Control ctrl in this.Controls)
{
if( ctrl is Textbox )
{
ctrl.ResetText();
}
}
Enjoy!
Updated:
December 08 2008 16:59:00 EST
Tags:
Snippet
,
Foreach
,
Type comparison
Back to top •
Comments ( 0 ) •
Login to comment.
Blog
How-To
Code
Web
Sorry. There are currently no comments for this article.