public static void ClearAllTextBoxes(Control parent)
{
foreach (Control ctrl in parent.Controls)
{
if (ctrl is TextBox txt)
{
txt.Text = string.Empty;
}
else if (ctrl.HasControls())
{
ClearAllTextBoxes(ctrl); // 遞迴進入子控制項集合
}
}
}
protected void btnClear_Click(object sender, EventArgs e)
{
ClearAllTextBoxes(this.Page); // 或 this.Master.FindControl("ContentPlaceHolder1")
}
public static void ClearTextControls(Control parent)
{
foreach (Control ctrl in parent.Controls)
{
if (ctrl is ITextControl textCtrl)
textCtrl.Text = string.Empty;
else if (ctrl.HasControls())
ClearTextControls(ctrl);
}
}
涵蓋 TextBox、Label、Literal 等。
HasControls 檢查可避免不必要的遞迴呼叫。UpdatePanel,確保清除觸發非同步回傳或手動 UpdatePanel.Update()。public static void ClearValidators(Control parent)
{
foreach (Control ctrl in parent.Controls)
{
if (ctrl is BaseValidator v) v.IsValid = true;
else if (ctrl.HasControls()) ClearValidators(ctrl);
}
}