How to clear all textboxes text in windows forms using foreach loop in C#.net || Example to Clear all textboxes text using foreach loop window forms in C#


To clear all textboxes text easily by using foreach loop.

For example if we have more than one textboxes in our form  and we have to clear all textboxes when we click on  clear button, then write the following code in clear button click event using foreach loop.

private void btnClear_Click(object sender, EventArgs e)
        {

            foreach (Control X in this.Controls)
            {
                if (X is TextBox)
                    X.Text = " ";

            }
       
        }

6 comments:

  1. this code working ... try correctly

    ReplyDelete
  2. Above Code is not Working...

    Following code is working :->

    protected void btnsubmit_Click(object sender, EventArgs e)
    {
    ResetFormControlValues(this);

    }

    private void ResetFormControlValues(Control parent)
    {
    foreach (Control c in parent.Controls)
    {
    if (c.Controls.Count > 0)
    {
    ResetFormControlValues(c);
    }
    else
    {
    switch (c.GetType().ToString())
    {
    case "System.Web.UI.WebControls.TextBox": ((TextBox)c).Text = "";
    break;
    case "System.Web.UI.WebControls.DropDownList": ((DropDownList)c).Text = "";
    break;
    case "System.Web.UI.WebControls.CheckBox":
    ((CheckBox)c).Checked = false;
    break;
    case "System.Web.UI.WebControls.RadioButton": ((RadioButton)c).Checked = false;
    break;

    }
    }
    }
    }

    ReplyDelete
  3. This code is also not working....

    ReplyDelete
  4. its working fine

    don't gap between x.text="";

    foreach (Control X in this.Controls)
    {
    if (X is TextBox)
    X.Text = "";

    }
    100% working

    ReplyDelete
  5. 100% works man!!!
    thanks a ton. . . :)

    ReplyDelete