由於項目收尾,最近忙著做一些方法的優化,整理了一些分享給大家。
當頁面內有許多控件,我們在需要清空其值的時候,一個個清空未免太麻煩。於是寫了這麼一個方法,可以自定義清空控件的類型,靈活應對業務需求。
復制代碼 代碼如下:
/// <summary>重置方法控件類型枚舉</summary>
/// <remarks>求知域http://www.qqextra.com 2012-12-28</remarks>
public enum ReSetType
{
/// <summary>
/// TextBox
/// </summary>
TXT,
/// <summary>
/// DropDownList
/// </summary>
DDL,
/// <summary>
/// RadioButtonList
/// </summary>
RBL,
/// <summary>
/// 全部ReSetType類型
/// </summary>
ALL
}
/// <summary>重置控件的值</summary>
/// <remarks>求知域http://www.qqextra.com 2012-12-28</remarks>
/// <param name="control">this</param>
/// <param name="rst">ReSetType.ALL為清空ReSetType枚舉中包含的所有控件類型</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)
{
//文本框
if (c is TextBox && blTxt == true)
{
((TextBox)c).Text = "";
}
else
//下拉列表
if (c is DropDownList && blDdl == true)
{
DropDownList ddl = (DropDownList)c;
if (ddl.Items.Count > 0)
{
ddl.SelectedIndex = 0;
}
}
else
//單選按鈕列表
if (c is RadioButtonList && blRbl == true)
{
((RadioButtonList)c).SelectedIndex = -1;
}
else
if (c.HasControls())
{
//遞歸
ReSet(c, rst);
}
}
}