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






4.43/5 (7 votes)
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);
}