Subscribe

RSS Feed (xml)

Process All the Controls on a Form

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);
        }
    }
}

No comments:

Post a Comment

Archives

LocalsAdda.com-Variety In Web World

Fun Mail - Fun in the Mail