How to disable (make read only) a cell in a DataGridView CheckBox column based on the value in other cells?
To handle the changes in column name, you can use the DataGridView.CellValueChanged
event. The e
parameter give you access to:
columnIndex
property, so you can test if the change is made on the name column (index 1).rowIndex
property, so you retrieve the concerned row and change the values you want.
private void DataGridView1_CellValueChanged(object sender, System.Windows.Forms.DataGridViewCellEventArgs e)
{
//second column
if (e.ColumnIndex == 1) {
object value = DataGridView1.Rows[e.RowIndex].Cells[e.ColumnIndex].Value;
if (value != null && value.ToString() != string.Empty) {
DataGridView1.Rows[e.RowIndex].Cells[2].ReadOnly = false;
} else {
DataGridView1.Rows[e.RowIndex].Cells[2].ReadOnly = true;
}
}
}
EDIT
As someone else noted, in order to have the checkbox
disabled for new added rows (especially if the AllowUserToAddRow
property is set to true
), you can handle the RowAdded
event:
private void dataGridView1_RowsAdded(object sender, DataGridViewRowsAddedEventArgs e)
{
DataGridView1.Rows[e.RowIndex].Cells[2].ReadOnly = true;
}
Quite old thread but I think you can use CellBeginEdit event and Cancel the event on your condition. It is not disable the column it is rather cancel editing the desired column value.
1) subscribe for the event:
this.dataGridView1.CellBeginEdit += DataGridView1OnCellBeginEdit;
2) event handler:
private void DataGridView1OnCellBeginEdit(object sender, DataGridViewCellCancelEventArgs args)
{
var isTicked = this.dataGridView1.Rows[args.RowIndex].Cells[args.ColumnIndex].Value;
args.Cancel = (isTicked is bool) && ((bool)isTicked);
}
I have used the event to get one inclusive checkbox.
It means only one out of the three columns("None", "Read", "Full") can be "true"
You can use DataGridView.CellValueChanged event:
private void dataGridView1_CellValueChanged(object sender, DataGridViewCellEventArgs e)
{
if (e.RowIndex >= 0)
{
if (e.ColumnIndex == 1 && dataGridView1[1, e.RowIndex].Value.ToString() != "")
dataGridView1[2, e.RowIndex].ReadOnly = false;
else
dataGridView1[2, e.RowIndex].ReadOnly = true;
}
}
But in order to have the checkbox disbled at first, make sure you set the column to be ReadOnly using the designer and also, in the DataGridView.RowsAdded event, set the checkbox property ReadOnly = true for the new created row:
private void dataGridView1_RowsAdded(object sender, DataGridViewRowsAddedEventArgs e)
{
dataGridView1[2, e.RowIndex].ReadOnly = true;
}