How to Clear the Text of All Textboxes in the Form

Clear all textboxes at once in winform

this method clear all textbox from WinForm

void ClearTextboxes(System.Windows.Forms.Control.ControlCollection ctrls)
{
foreach (Control ctrl in ctrls)
{
if (ctrl is TextBox)
((TextBox)ctrl).Text = string.Empty;
ClearTextboxes(ctrl.Controls);
}
}

and you can call it

private void btnReset_Click(object sender, EventArgs e)
{
ClearTextboxes();
txtFname.Focus();
}

How to clear all textboxes in a Web Form? (The name 'form1' does not exist in the current context)

The textboxes were inside a content placeholder. The code below worked.

        void cleanFields()
{
foreach (Control item in Page.Form.FindControl("ContentPlaceHolder1").Controls)
{
if (item is TextBox)
{
((TextBox)item).Text = string.Empty;
}
}

}

Clear all textbox in a windows form except special ones

Shorter version of GetAllChildren:

protected static IEnumerable<Control> GetAllChildren(Control root) {
return new Control[] { root }
.Concat(root.Controls
.OfType<Control>()
.SelectMany(item => GetAllChildren(item)));
}

And shorter Linq:

var source = GetAllChildren(root)
.OfType<TextBox>()
.Where(ctrl => !except.Contains(ctrl));

foreach (var textBox in source)
textBox.Text = resetWith;

The problem with your current implmentation is in the inner loop:

foreach (TextBox txtException in except)
if (txtException.Name != txt.Name)
txt.Text = resetWith == "" ? string.Empty : resetWith;

if you have at least two exceptions with different names that condition

 txtException.Name != txt.Name

will be inevitably satisfied (any txt.Name either not equal 1st exception or 2nd one)

Clear multiple text boxes with a button in C#

void ClearAllText(Control con)
{
foreach (Control c in con.Controls)
{
if (c is TextBox)
((TextBox)c).Clear();
else
ClearAllText(c);
}
}

To use the above code, simply do this:

ClearAllText(this);

Any way to clear all fields in a form at once?

You can use the following loop to clear all the textbox objects in your active form:

foreach (Control c in this.Controls) 
{
if (c.GetType() == typeof(TextBox))
{
c.Clear();
}
}

You can also use the loop inside a function and give it a Boolean return value to test if it was successfuly executed.

Clear all TextBoxes texts

Try this code:

void ClearTextBoxes(Control parent)
{
foreach (Control child in parent.Controls)
{
TextBox textBox = child as TextBox;
if (textBox == null)
ClearTextBoxes(child);
else
textBox.Text = string.Empty;
}
}

private void ClearButton_Click(object sender, EventArgs e)
{
ClearTextBoxes(tabControl1.SelectedTab);
}


Related Topics



Leave a reply



Submit