由於項目收尾,最近忙著做一些方法的最佳化,整理了一些分享給大家。
當頁面內有許多控制項,我們在需要清空其值的時候,一個個清空未免太麻煩。於是寫了這麼一個方法,可以自訂清空控制項的類型,靈活應對業務需求。
複製代碼 代碼如下:
/// <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);
}
}
}