Visual Basic Coding Like Forrest Gump

An Interesting Use of a C# Foreach Loop

Posted November 4, 2008 in Blog by Tieson

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!

Add Comment:

Remember: If you can't say anything nice, don't say it at all... :D

Updated: July 17, 2009 ↑Back to top

Visual Basic Coding Like Forrest Gump

A programmer is a person who passes as an exacting expert on the basis of being able to turn out, after innumerable punching, an infinite series of incomprehensible answers calculated with micrometric precisions from vague assumptions based on debatable figures taken from inconclusive documents and carried out on instruments of problematical accuracy by persons of dubious reliability and questionable mentality for the avowed purpose of annoying and confounding a hopelessly defenseless department that was unfortunate enough to ask for the information in the first place.

~ IEEE Grid Newsmagazine ( unknown publication date )