[英]Read Only Columns & Rows in a DataGridView
I have a datagridview in a WinForms application and I want all columns bar one to be locked to editing. 我在WinForms应用程序中有一个datagridview,我希望所有列栏都被锁定为编辑。 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 ColA ColB ColC
row1 true value1 row1 true value1
row2 false value2 row2 false value2
row3 true value3 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. 我希望列A和B完全锁定(只读),并且Col C的默认值允许编辑,除非列B中的值为false。 Hence in the above example only value1 and value3 would be editable.
因此,在上面的示例中,只有value1和value3可以编辑。
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. 但是我似乎无法实现这一点,因为如上所述,如果我使用将readonly设置为false的条件循环遍历行,则所有内容都将被锁定。
The code you have shown should not compile and also isn't correctly examining the values within boolean cells in a DataGridView
. 您显示的代码不应该编译,也不能正确检查
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 它按预期工作
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.