如何使一个单元格只读?

问题描述 投票:0回答:1

不是整行,不是整列,只是一个单元格。

DataGridView
ReadOnly 属性设置为 false(默认)。如果在行级别满足条件,则允许特定单元格为只读 false/true

foreach (DataGridViewRow row in dgv.Rows)
{
    if (!Convert.ToBoolean(row.Cells["Cell 0"].Value))
    {
        row.Cells["Cell 3"].ReadOnly = false;  // The Cell 3 for the current row (only this row, only this cell)
                                               // is set to ReadOnly = false
    }
    else
    {
        row.Cells["Cell 3"].ReadOnly = true;  // The Cell 3 for the current row (only this row, only this cell)
                                              // is set to ReadOnly = true
    }
}
c# winforms datagridview
1个回答
1
投票

您在

row.Cells[]
中提供的标识符不正确。您应该在那里提供列名称而不是单元格名称!

示例:

dataGridView1.Rows.Add("test", "false");
dataGridView1.Rows.Add("sfsdf", "true");
dataGridView1.Rows.Add("hjdfg", "false");

foreach (DataGridViewRow row in dataGridView1.Rows)
{
    // Will check the value of the cell in current row and column "Column2"
    if (Convert.ToBoolean(row.Cells["Column2"].Value))
        row.Cells["Column2"].ReadOnly = true; // Sets the property of that cell
}

如果您愿意,可以缩短该代码以将特定列中的所有单元格的

readonly
属性设置为特定单元格值:

row.Cells["Column2"].ReadOnly = Convert.ToBoolean(row.Cells["Column2"].Value);
© www.soinside.com 2019 - 2024. All rights reserved.