建立 ColumnState Class 來當成傳遞參數
namespace CheckBox2ShowColumn2 { public class ColumnState { public string ColName{get;set;} public Boolean ColVisible{get;set;} } }
Grid 為開始 Form,使用者可以自由變更 DataGridView 欄位數
namespace CheckBox2ShowColumn2 { public partial class Grid : Form { public Grid() { InitializeComponent(); } private void btnShow_Click(object sender, EventArgs e) { List<columnstate> csLists = new List<columnstate>(); foreach (DataGridViewColumn col in dgvColumns.Columns) { ColumnState cs = new ColumnState(); cs.ColName = col.Name; cs.ColVisible = col.Visible; csLists.Add(cs); } ColumnCheck frmshow = new ColumnCheck(csLists); // 沒有按下 ColumnCheck Form 中的完成按鈕,就必須 return if (frmshow.ShowDialog() != DialogResult.OK) return; // 抓取 ColumnCheck 中的 Result 並根據它來顯示 DataGridView 欄位 foreach (ColumnState cs in frmshow.getResult()) { dgvColumns.Columns[cs.ColName].Visible = cs.ColVisible; } } } }ColumnCheck Form 內會動態利用 CheckBox 顯示 Grid Form 內 DataGridView 欄位名稱,讓使用者可以勾選要顯是哪些欄位
namespace CheckBox2ShowColumn2 { public partial class ColumnCheck : Form { public ColumnCheck() { InitializeComponent(); } #region Result 回傳值 private List<ColumnState> Result = new List<ColumnState>(); private void setResult() { foreach (CheckBox item in grpCheckBox.Controls) { ColumnState cs = new ColumnState(); cs.ColName = item.Name; cs.ColVisible = item.Checked; Result.Add(cs); } } public List<ColumnState> getResult() { return Result; } #endregion public ColumnCheck(List<ColumnState> _csLists) { InitializeComponent(); int ColumnAdd = 0; int TopAdd = 0; int LeftAdd = 0; int index = 0; foreach (ColumnState item in _csLists) { // 動態建立 CheckBox CheckBox cb = new CheckBox(); cb.Visible = true; cb.AutoSize = true; cb.Text = item.ColName; cb.Name = item.ColName; cb.Checked = item.ColVisible; // 每 5 個 Column 一欄,因此利用 % 來重覆計算 index = _csLists.IndexOf(item) % 5; if(index == 0) ColumnAdd++; TopAdd = index * 20; LeftAdd = ColumnAdd * 100; cb.Left = grpCheckBox.Left + LeftAdd; cb.Top = grpCheckBox.Top + TopAdd; grpCheckBox.Controls.Add(cb); } } private void btnOK_Click(object sender, EventArgs e) { // 離開此 Form 前,必須把 grpCheckBox 內 CheckBox 值,丟回 Result setResult(); // 關閉 Form this.DialogResult = DialogResult.OK; } } }
- 預設有 11 個欄位
- 每 5 個欄位一欄
- 參考資料
- 論壇問題出處
沒有留言:
張貼留言