6.3 Process All the Controls on a Form


Problem

You need to perform a generic task with all the controls on the form (for example, retrieving or clearing their Text property, changing their color , or resizing them).

Solution

Iterate recursively through the collection of controls. Interact with each control using the properties and methods of the base Control class.

Discussion

You can iterate through the controls on a form using the Form.Controls collection, which includes all the controls that are placed directly on the form surface. However, if any of these controls are container controls (such as GroupBox , Panel , or TabPage ), they might contain more controls. Thus, it's necessary to use recursive logic that searches the Controls collection of every control on the form.

The following example shows a form that performs this recursive logic to find every text box on a form and clears the text they contain. The form tests each control to determine whether it's a text box by using the typeof operator.

 using System; using System.Windows.Forms; public class ProcessAllControls : System.Windows.Forms.Form {     // (Designer code omitted.)     private void cmdProcessAll_Click(object sender, System.EventArgs e) {         ProcessControls(this);     }     private void ProcessControls(Control ctrl) {              // Ignore the control unless it's a text box.         if (ctrl.GetType() == typeof(TextBox)) {             ctrl.Text = "";         }                  // Process controls recursively.          // This is required if controls contain other controls         // (for example, if you use panels, group boxes, or other         // container controls).         foreach (Control ctrlChild in ctrl.Controls) {             ProcessControls(ctrlChild);         }     } } 



C# Programmer[ap]s Cookbook
C# Programmer[ap]s Cookbook
ISBN: 735619301
EAN: N/A
Year: 2006
Pages: 266

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net