I have a datagridview in a WinForms application and I want all columns bar one to be locked to editing. This I was able to achieve with the following code:
foreach (DataGridViewColumn col in myGrid.Columns)
{
if (col.Name == "LockedColumn")
{
col.ReadOnly = false;
}
else
{
col.ReadOnly = true;
}
}
However, I also need a conditional lock on this column, dependent on the values elsewhere in each row. I tried the following code:
foreach (DataGridViewRow row in myGrid.Rows)
{
if ((bool)row.Cells["ConditionalColumn"].Value == false)
{
row.ReadOnly = false;
}
else
{
row.ReadOnly = true;
}
}
However this locks the whole grid which is not what I want. What I'm after may be clearer with a table example.
ColA ColB ColC
row1 true value1
row2 false value2
row3 true value3
I want Columns A & B locked (read only) in their entirety, and the default for Col C to allow editing, except where the value in Column B is false. Hence in the above example only value1 and value3 would be editable.
However I can't seem to achieve this, because as stated above, if I loop through the rows with a condition that sets readonly to false, everything is locked.
It was the following line that was the issue
row.ReadOnly = false;
When changed to
row.Cells["colName"].ReadOnly = false;
it works as intended