1,編輯DataGridView,添加一列 CheckBox ,Name 賦值爲 "select",以下圖:spa
2,取消 datagridview 的可編輯屬性,添加 CellClick 事件,用代碼來控制checkbox的選中狀態,具體代碼以下:code
private void dataGridView1_CellClick(object sender, DataGridViewCellEventArgs e) { if (e.RowIndex == -1 || e.ColumnIndex == -1) return; if (dataGridView1.Columns[e.ColumnIndex].Name != "select") return; DataGridViewCheckBoxCell cell = (DataGridViewCheckBoxCell)dataGridView1.Rows[e.RowIndex].Cells[e.ColumnIndex]; if (cell.Value != null && (bool)cell.Value) { cell.Value = false; } else { cell.Value = true; } }
3,爲datagridview關聯一個右鍵菜單,具體的如何獲取datagridview中checkbox選中的行代碼以下:blog
private List<AlarmModel> GetAlarmConfirmModelsByDGVCheckbox() { List<AlarmModel> alarmModels = new List<AlarmModel>(); foreach (DataGridViewRow row in dataGridView1.Rows) { if (row.Cells["select"].Value != null && (bool)row.Cells["select"].Value) { AlarmModel model = row.DataBoundItem as AlarmModel; if (model == null) continue; alarmModels.Add(model); } } return alarmModels.Count == 0 ? null : alarmModels; }