下圖為控件 TabIndex 的顯示圖,請 CheckBox 依序從 1 排到 5
namespace CheckBox2ShowColumn { public partial class Demo : Form { public Demo() { InitializeComponent(); } private void Demo_Load(object sender, EventArgs e) { // 用三種方法來練習,使用方法二和三,必須先把 Load 內的方法一 Code 先 comment 起來 chkCol1.Checked = true; chkCol2.Checked = true; chkCol3.Checked = true; chkCol4.Checked = true; chkCol5.Checked = true; // 方法一:直接利用 CheckBox.Checked 來判斷欄位顯示 //chkCol1.CheckedChanged += chkCol1_CheckedChanged; //chkCol2.CheckedChanged += chkCol1_CheckedChanged; //chkCol3.CheckedChanged += chkCol1_CheckedChanged; //chkCol4.CheckedChanged += chkCol1_CheckedChanged; //chkCol5.CheckedChanged += chkCol1_CheckedChanged; } void chkCol1_CheckedChanged(object sender, EventArgs e) { bool chked = ((CheckBox)sender).Checked; int tabindex = ((CheckBox)sender).TabIndex; // 根據論壇問題用 tabindex 來抓取 dgvColumnShow 內的欄位 dgvColumnShow.Columns[tabindex - 1].Visible = chked; } // 方法二:利用 for 迴圈來掃 Form 內的 CheckBox 控件 private void btnFor_Click(object sender, EventArgs e) { for (int i = 0; i < this.Controls.Count; i++) { if (!(this.Controls[i] is CheckBox)) continue; CheckBox chk = this.Controls[i] as CheckBox; if (chk == null) continue; bool chked = chk.Checked; int tabindex = chk.TabIndex; dgvColumnShow.Columns[tabindex - 1].Visible = chked; } } // 方法三:利用 foreach 迴圈來掃 Form 內的 CheckBox 控件 private void btnForeach_Click(object sender, EventArgs e) { foreach (CheckBox item in this.Controls.OfType<checkbox>()) { bool chked = item.Checked; int tabindex = item.TabIndex; dgvColumnShow.Columns[tabindex - 1].Visible = chked; } } } }
- 參考資料
- 論壇問題出處
沒有留言:
張貼留言