在Datagridview中启用和禁用单元格

20 .net datagridview

我正在使用DataGridView控件来显示一些数据.我需要启用一些数据并根据网格中的某些值动态禁用某些数据.

谁能告诉我怎么做?

Vic*_*scu 39

要"禁用"一个单元格,它必须是只读的并以某种方式变灰.此函数启用/禁用DataGridViewCell:

    /// <summary>
    /// Toggles the "enabled" status of a cell in a DataGridView. There is no native
    /// support for disabling a cell, hence the need for this method. The disabled state
    /// means that the cell is read-only and grayed out.
    /// </summary>
    /// <param name="dc">Cell to enable/disable</param>
    /// <param name="enabled">Whether the cell is enabled or disabled</param>
    private void enableCell(DataGridViewCell dc, bool enabled) {
        //toggle read-only state
        dc.ReadOnly = !enabled;
        if (enabled)
        {
            //restore cell style to the default value
            dc.Style.BackColor = dc.OwningColumn.DefaultCellStyle.BackColor;
            dc.Style.ForeColor = dc.OwningColumn.DefaultCellStyle.ForeColor;
        }
        else { 
            //gray out the cell
            dc.Style.BackColor = Color.LightGray;
            dc.Style.ForeColor = Color.DarkGray;
        }
    }
Run Code Online (Sandbox Code Playgroud)

  • 仍然可以选择一个单元格 - 导致灰色消失。解决方案是同时设置 dc.Style.SelectionBackColor 和 dc.Style.SelectionForeColor 属性。单元格仍处于选中状态,只是没有混乱的视觉变化(无论如何您都无法更改复选框) (2认同)

Blo*_*ard 16

您可以将特定行或单元格设置为只读,因此用户无法更改该值.你是这个意思吗?

dataGridView1.Rows[0].ReadOnly = true;
dataGridView1.Rows[1].Cells[2].ReadOnly = true;
Run Code Online (Sandbox Code Playgroud)