C# DataGridViewCheckBoxColumn Hide/Gray-Out

后端 未结 3 821
既然无缘
既然无缘 2021-01-13 17:21

I have a DataGridView with several columns and several rows of data. One of the columns is a DataGridViewCheckBoxColumn and (based on the other dat

3条回答
  •  青春惊慌失措
    2021-01-13 17:37

    Taken from Customize the Appearance of Cells in the Windows Forms DataGridView Control, you could catch the CellPainting event and not draw the cell if its in read only mode. For example:

    public Form1()
    {
       InitializeComponent();
       dataGridView1.CellPainting += new 
          DataGridViewCellPaintingEventHandler(dataGridView1_CellPainting);
    }
    
    private void dataGridView1_CellPainting(object sender,
       System.Windows.Forms.DataGridViewCellPaintingEventArgs e)
    {
       // Change 2 to be your checkbox column #
       if (this.dataGridView1.Columns[2].Index == e.ColumnIndex && e.RowIndex >= 0)
       {
          // If its read only, dont draw it
          if (dataGridView1[e.ColumnIndex, e.RowIndex].ReadOnly)
          {
             // You can change e.CellStyle.BackColor to Color.Gray for example
             using (Brush backColorBrush = new SolidBrush(e.CellStyle.BackColor))
             {
                // Erase the cell.
                e.Graphics.FillRectangle(backColorBrush, e.CellBounds);
                e.Handled = true;
             }
          }
       }
    }
    

    The only caveat is that you need to call dataGridView1.Invalidate(); when you change the ReadOnly property of one of the DataGridViewCheckBox cell's.

提交回复
热议问题