[c#] How to clear the text of all textBoxes in the form?

private void CleanForm()
{
    foreach (var c in this.Controls)
    {
        if (c is TextBox)
        {
            ((TextBox)c).Text = String.Empty;
        }
    }
}

This method above doesn't work and the controls aren't cleared. It compiles fine, but does nothing.

Any ideas?

This question is related to c# winforms textbox

The answer is


Try this:

var t = this.Controls.OfType<TextBox>().AsEnumerable<TextBox>();
foreach (TextBox item in t)
{
    item.Text = "";
}

private void CleanForm(Control ctrl)
{
    foreach (var c in ctrl.Controls)
    {
        if (c is TextBox)
        {
            ((TextBox)c).Text = String.Empty;
        }

        if( c.Controls.Count > 0)
        {
           CleanForm(c);
        }
    }
}

When you initially call ClearForm, pass in this, or Page (I assume that is what 'this' is).


I like lambda :)

 private void ClearTextBoxes()
 {
     Action<Control.ControlCollection> func = null;

     func = (controls) =>
         {
             foreach (Control control in controls)
                 if (control is TextBox)
                     (control as TextBox).Clear();
                 else
                     func(control.Controls);
         };

     func(Controls);
 }

Good luck!


Maybe you want more simple and short approach. This will clear all TextBoxes too. (Except TextBoxes inside Panel or GroupBox).

 foreach (TextBox textBox in Controls.OfType<TextBox>())
    textBox.Text = "";

I improved/fixed my extension method.

public  static class ControlsExtensions
{
    public static void ClearControls(this Control frm)
    {
        foreach (Control control in frm.Controls)
        {
            if (control is TextBox)
            {
                control.ResetText();
            }

            if (control.Controls.Count > 0)
            {
                control.ClearControls();
            }
        }
    }
}

You can try this code

protected override bool ProcessCmdKey(ref Message msg, Keys keyData)
    {


        if(keyData==Keys.C)
        {
            RefreshControl();
            return true;
        }


        return base.ProcessCmdKey(ref msg, keyData);
    }

And this for clearing all controls in form like textbox, checkbox, radioButton

you can add different types you want..

private void ClearTextBoxes(Control control)
    {
        foreach (Control c in control.Controls)
        {
            if (c is TextBox)
            {
                ((TextBox)c).Clear();
            }

            if (c.HasChildren)
            {
                ClearTextBoxes(c);
            }


            if (c is CheckBox)
            {

                ((CheckBox)c).Checked = false;
            }

            if (c is RadioButton)
            {
                ((RadioButton)c).Checked = false;
            }
        }
    }

We had a problem like this some weeks before. If you set a breakpoint and have a deep look into this.Controls, the problem reveals it's nature: you have to recurse through all child controls.

The code could look like this:

private void CleanForm()
{
    traverseControlsAndSetTextEmpty(this);
}
private void traverseControlsAndSetTextEmpty(Control control)
{

    foreach(var c in control.Controls)
    {
        if (c is TextBox) ((TextBox)c).Text = String.Empty;
        traverseControlsAndSetTextEmpty(c);
    }
}

Your textboxes are probably inside of panels or other containers, and not directly inside the form.

You need to recursively traverse the Controls collection of every child control.


Examples related to c#

How can I convert this one line of ActionScript to C#? Microsoft Advertising SDK doesn't deliverer ads How to use a global array in C#? How to correctly write async method? C# - insert values from file into two arrays Uploading into folder in FTP? Are these methods thread safe? dotnet ef not found in .NET Core 3 HTTP Error 500.30 - ANCM In-Process Start Failure Best way to "push" into C# array

Examples related to winforms

How to set combobox default value? Get the cell value of a GridView row Getting the first and last day of a month, using a given DateTime object Check if a record exists in the database Delete a row in DataGridView Control in VB.NET How to make picturebox transparent? Set default format of datetimepicker as dd-MM-yyyy Changing datagridview cell color based on condition C# Inserting Data from a form into an access Database How to use ConfigurationManager

Examples related to textbox

Add two numbers and display result in textbox with Javascript How to check if a text field is empty or not in swift Setting cursor at the end of any text of a textbox Press enter in textbox to and execute button command javascript getting my textbox to display a variable How can I set focus on an element in an HTML form using JavaScript? jQuery textbox change event doesn't fire until textbox loses focus? PHP: get the value of TEXTBOX then pass it to a VARIABLE How to clear a textbox once a button is clicked in WPF? Get current cursor position in a textbox