65.9K
CodeProject is changing. Read more.
Home

How to clear a Multiple TextBox values in a single click in C# .NET

starIconstarIconstarIconstarIcon
emptyStarIcon
starIcon

4.43/5 (7 votes)

Sep 22, 2011

CPOL
viewsIcon

16101

A generic text clear method for those ASP.NET controls which implement the ITextControl interface:private void Clear(ControlCollection controlCollection) where T : ITextControl{ if (controlCollection == null) return; ...

A generic text clear method for those ASP.NET controls which implement the ITextControl interface:

private void Clear<T>(ControlCollection controlCollection)
    where T : ITextControl
{
    if (controlCollection == null) return;
    controlCollection.Cast<Control>().ToList().ForEach(control =>
    {
        var textCollection = control.Controls.OfType<T>();
        if (textCollection.Count() > 0)
        {
            textCollection.ToList<T>().ForEach(textBox => textBox.Text = string.Empty);
        }
    });
}

Usage: a button click from an ASP.NET page:

protected void btnClear_Click(object sender, EventArgs e)
{
    Clear<TextBox>(Page.Controls);
}