The CheckBox column is added to the DataGridView datagrito select rows.
Add the CheckBox column in The DataGridView to select rows.
1. Edit the DataGridView and add a CheckBox column. The value of Name is "select", for example:
2. Cancel the Editable attribute of the datagridview datagri, Add the CellClick event, and use code to control the selected status of the checkbox. The specific code is as follows:
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. associate a right-click menu for the dview datagri. the code for how to obtain the row selected by the checkbox in the datagridview dview is as follows:
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; }