How to clear all TextBox in a Windows Form?

  • Thread starter Thread starter Jason Huang
  • Start date Start date
J

Jason Huang

Hi,

In my C# Windows Form MyForm, it has many TextBoxes, e.g., txtName, txtID,
txtAddress, ...,
it also has many ComboBoxes, e.g., cboState, cboGender.
How do I clear all those controls's Text in a function? Is it possible to
do it in foreach loop?
Thanks for help.



Jason
 
Hi Jason,
it is possible to clear all them at once but you will have to write
recursive function becaues some controls could be in subcontainers

you could use

public ClearConent(Control parent)
foreach(Control ctl in parent.Controls)
{
//clear contained controls
if (ctlControls.Count > 0) ClearConent(ctl);

if(ctl is Textbox) ((TextBox)ctl).Text = string.Empty;
elseif (ctl is CheckBox) ((CheckBox))ctl).Checked = false;

}

Hope this help
Galin Iliev [MCSD.NET]
 
Hi Jason,

Try this loop:
private void button1_Click(object sender, EventArgs e)

{

foreach (Control c in this.Controls)

if (c is TextBox)

(c as TextBox).Clear();

}


Regards - Octavio
 
Hi,

Jason Huang said:
Thanks!
How about some TextBoxes and ComboBoxes in a GoupBox?
It will work the same, also with Panel , and any other grouping control.
 
Back
Top