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.
The code you have shown should not compile and also isn't correctly examining the values within boolean cells in a DataGridView
.
If you change your code to look at rows to something like the code below then you should be able to set individual rows to read only based on the column:
foreach (DataGridViewRow row in myGrid.Rows)
{
if (row.Cells["ConditionalColumn"].Value == null || (bool)row.Cells["ConditionalColumn"].Value == false)
{
row.ReadOnly = false;
}
else
{
row.ReadOnly = true;
}
}
It was the following line that was the issue
row.ReadOnly = false;
When changed to
row.Cells["colName"].ReadOnly = false;
it works as intended
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.