winforms 如何使一个单元格为只读?

omjgkv6w  于 2023-08-07  发布在  其他
关注(0)|答案(1)|浏览(114)

不是整行,不是整列,只是一个单元格。DataGridView ReadOnly属性设置为false(默认值)。如果在行级别满足条件,则允许特定单元格为ReadOnly 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
    }
}

字符串

qfe3c7zg

qfe3c7zg1#

您在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);

相关问题