Asp.net method to clear control values of customizable control types

  • 2020-06-01 09:32:33
  • OfStack

Due to the project closure, I have been busy with the optimization of some methods recently, and I have sorted out some of them to share with you.

When there are so many controls on a page that we need to empty them, it's too much trouble to empty them all. So I wrote a method that can customize the type of the clear control and flexibly respond to business requirements.
 
/// <summary> Reset method control type enumeration </summary> 
/// <remarks> Domain knowledge http://www.qqextra.com 2012-12-28</remarks> 
public enum ReSetType 
{ 
/// <summary> 
/// TextBox 
/// </summary> 
TXT, 
/// <summary> 
/// DropDownList 
/// </summary> 
DDL, 
/// <summary> 
/// RadioButtonList 
/// </summary> 
RBL, 
/// <summary> 
///  all ReSetType type  
/// </summary> 
ALL 
} 
/// <summary> Reset the value of the control </summary> 
/// <remarks> Domain knowledge http://www.qqextra.com 2012-12-28</remarks> 
/// <param name="control">this</param> 
/// <param name="rst">ReSetType.ALL For empty ReSetType All the control types contained in the enumeration </param> 
public static void ReSet(Control control, params ReSetType[] rst) 
{ 
bool blTxt = false; 
bool blDdl = false; 
bool blRbl = false; 
foreach (ReSetType type in rst) 
{ 
if (type == ReSetType.ALL) 
{ 
blTxt = true; 
blDdl = true; 
blRbl = true; 
break; 
} 
else 
if (type == ReSetType.TXT) 
blTxt = true; 
else if (type == ReSetType.DDL) 
blDdl = true; 
else if (type == ReSetType.RBL) 
blRbl = true; 
} 
foreach (Control c in control.Controls) 
{ 
// The text box  
if (c is TextBox && blTxt == true) 
{ 
((TextBox)c).Text = ""; 
} 
else 
// The drop-down list  
if (c is DropDownList && blDdl == true) 
{ 
DropDownList ddl = (DropDownList)c; 
if (ddl.Items.Count > 0) 
{ 
ddl.SelectedIndex = 0; 
} 
} 
else 
// List of radio buttons  
if (c is RadioButtonList && blRbl == true) 
{ 
((RadioButtonList)c).SelectedIndex = -1; 
} 
else 
if (c.HasControls()) 
{ 
// recursive  
ReSet(c, rst); 
} 
} 
} 

Related articles: