How to clear all TextBox in a Windows Form?

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
 
G

Galcho[MCSD.NET]

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]
 
O

Octavio Hernandez

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
 
I

Ignacio Machin \( .NET/ C# MVP \)

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.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top