//'______________________________________________________________ //' C O N T R O L S C O L L E C T I O N D E M O //' Ron Kessler //' Created 9/24/08 //'______________________________________________________________ //'This demo shows how to cycle through the controls collection on a form to clear all testboxes. //'However, notice there is a textbox inside of a container control (Groupbox). The form's control //'collection will not see this textbox because it is inside a container control. So we will use the //'HasChildren property of the controls in the form's collection to find the nested controls! using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Text; using System.Windows.Forms; namespace Controls_Collection_Demo { public partial class frmMain : Form { public frmMain() { InitializeComponent(); } private void btnClear_Click(object sender, EventArgs e) { //---cycle through forms collection and clear textboxes foreach (Control myControl in this.Controls) { if (myControl is TextBox) myControl.Text = ""; else if (myControl.HasChildren) //if it comes across a groupbox or tab control that has child controls, clear textboxes & radiobuttons in them also { foreach (Control nestedControl in myControl.Controls) { if (nestedControl is TextBox) nestedControl.Text = ""; else if (nestedControl is RadioButton) { RadioButton myRadioButton = (RadioButton)nestedControl; //see note below myRadioButton.Checked = false; } } } } txtFirst.Focus(); } } // 'Note about the RadioButton loop above: //'All controls have a text property (I think). But not all controls have a Checked property. So to //'uncheck a RadioButton or Checkbox Control, I have to create a new reference variable (myRadioButton) line 52 //'and assign it to the current control being pointed to in nestedControl. Then I can access its checked //'property and uncheck it by making it false in line 53. }