在 Windows Forms 開發中,經常需要對表單或容器內的特定類型控制項(如所有 TextBox、所有 CheckBox)進行統一操作。使用 foreach 迴圈搭配型別檢查,能以簡潔程式碼實現批次處理,大幅提升開發效率。
foreach (型別 變數 in 集合)
{
// 操作變數
}
private void ClearAllTextBoxesInGroupBox(GroupBox groupBox)
{
foreach (Control ctrl in groupBox.Controls)
{
// 方式一:使用 is 型別模式比對 (C# 7.0+ 推薦)
if (ctrl is TextBox textBox)
{
textBox.Text = string.Empty;
textBox.Focus(); // 可額外操作
}
// 方式二:傳統 GetType 比對 (舊版本相容)
// if (ctrl.GetType() == typeof(TextBox))
// {
// ((TextBox)ctrl).Text = string.Empty;
// }
}
}
若控制項可能嵌套在 Panel、TabControl 等容器中,需遞迴遍歷:
private void ClearTextBoxesRecursive(Control parent)
{
foreach (Control ctrl in parent.Controls)
{
if (ctrl is TextBox textBox)
{
textBox.Text = string.Empty;
}
else if (ctrl.HasChildren) // 為容器控制項
{
ClearTextBoxesRecursive(ctrl); // 遞迴處理子控制項
}
}
}
// 使用方式
private void btnClearAll_Click(object sender, EventArgs e)
{
ClearTextBoxesRecursive(this); // 清空整個表單
}
| 操作需求 | 程式碼片段 |
|---|---|
| 啟用/停用所有按鈕 | if (ctrl is Button btn) btn.Enabled = false; |
| 取消勾選所有 CheckBox | if (ctrl is CheckBox cb) cb.Checked = false; |
| 設定所有 Label 字體顏色 | if (ctrl is Label lbl) lbl.ForeColor = Color.Red; |
| 收集所有 TextBox 文字 | var texts = new List |
is 關鍵字比 GetType() == typeof() 更快且支援繼承關係。foreach 中對 Controls 集合進行新增/刪除,會拋出例外。若需動態增刪,請先複製到 List<Control> 再操作。善用 foreach 迴圈配合型別模式比對,能以極少程式碼完成重複性控制項操作,減少手動逐一設定的錯誤機率,是 WinForms 開發的必備技巧。