private void DGV_DetailsViewer_CellContentClick(object sender, DataGridViewCellEventArgs e) { if (e.ColumnIndex.Equals(5)) { DataGridViewCheckBoxCell cbx = (DataGridViewCheckBoxCell)this.DGV_DetailsViewer.Rows[e.RowIndex].Cells[e.ColumnIndex]; MessageBox.Show(cbx.FormattedValue.ToString()); } }
The value of checkBoxCell read out by the above code is always False for unknown reasons.
The reason is: the CellContentClick event does not modify the value of CheckBoxCell, and this event does not work.
The correct approach should be to use a combination of the CurrentCellDirtyStateChanged event and the CellValueChanged event to accomplish this. code show as below:
// This event is executed first, even if the content of the modified checkboxcell takes effect immediately, otherwise it will only take effect when the cell is left. private void DGV_DetailsViewer_CurrentCellDirtyStateChanged( object sender, EventArgs e) { if (DGV_DetailsViewer.IsCurrentCellDirty) { DGV_DetailsViewer.CommitEdit(DataGridViewDataErrorContexts.Commit); } } // After the value is modified, execute this event. The function you want to implement is implemented in this event private void DGV_DetailsViewer_CellValueChanged( object sender, DataGridViewCellEventArgs e) { if (e.RowIndex >= 0 && e.RowIndex != -1 && !this.DGV_DetailsViewer.Rows[e.RowIndex].IsNewRow) { if (e.ColumnIndex.Equals(5)) { DataGridViewCheckBoxCell cbx = (DataGridViewCheckBoxCell)this.DGV_DetailsViewer.Rows[e.RowIndex].Cells[e.ColumnIndex]; MessageBox.Show(cbx.FormattedValue.ToString()); } } }