頁面包含大量 TextBox、DropDownList、RadioButtonList 等控制項,需提供「重置」功能,並能依業務需求指定清空哪些類型。
public enum ReSetType
{
TXT, // TextBox
DDL, // DropDownList
RBL, // RadioButtonList
ALL // 全部
}
public static void ReSet(Control control, params ReSetType[] rst)
{
bool doTxt = false, doDdl = false, doRbl = false;
foreach (var type in rst)
{
if (type == ReSetType.ALL) { doTxt = doDdl = doRbl = true; break; }
if (type == ReSetType.TXT) doTxt = true;
else if (type == ReSetType.DDL) doDdl = true;
else if (type == ReSetType.RBL) doRbl = true;
}
foreach (Control c in control.Controls)
{
if (doTxt && c is TextBox txt) txt.Text = "";
else if (doDdl && c is DropDownList ddl)
{
if (ddl.Items.Count > 0) ddl.SelectedIndex = 0;
}
else if (doRbl && c is RadioButtonList rbl) rbl.SelectedIndex = -1;
else if (c.HasControls()) ReSet(c, rst); // 遞迴處理子控制項
}
}
// 清空所有 TextBox 與 DropDownList
ReSet(this.Page, ReSetType.TXT, ReSetType.DDL);
// 清空全部支援類型
ReSet(this.Page, ReSetType.ALL);
// 僅清空 RadioButtonList
ReSet(this.Panel1, ReSetType.RBL);
CheckBoxList、ListBox、HiddenField 等類型至列舉。IResettable,讓使用者控制項自行實作 Reset()。DropDownList 重置為 SelectedIndex = 0,若第一項非預設值,建議改設 ClearSelection() 再手動選預設項。RadioButtonList.SelectedIndex = -1 可取消所有選取。