Pages

Wednesday, August 12, 2009

Clearing All Controls of a Form

Forms and Controls already have a property that list all controls contained within them called 'Controls'. 

You can iterate through this, checking each controls type and clearing them as appropriate. Note that some controls may have child controls and these would also need to be processed.

The following method can be used to clear all the controls


public void ClearControls(Control currentControl) 

foreach (Control myControl in currentControl.Controls) 

if (myControl.HasChildren) 

ClearControls(myControl); 


TextBox myTextBox = myControl as TextBox; 
if (myTextBox != null) 

myTextBox.Text = ""; 


RadioButton myRadioButton = myControl as RadioButton; 
if (myRadioButton != null) 

myRadioButton.Checked = false; 




Use ClearControls(this) from within the Form class


0 comments:

Post a Comment