26

I am using a DataGridView control for displaying some data. I need to enable some data and disable some data dynamically based on some values in the grid.

Can anyone tell me how to do it?

Blorgbeard
  • 101,031
  • 48
  • 228
  • 272

3 Answers3

46

To "disable" a cell, it must be read-only and grayed out somehow. This function enables/disables a 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;
        }
    }
Victor Ionescu
  • 1,967
  • 2
  • 21
  • 24
  • 3
    It is still possible to select a cell - resulting in the gray appearing to disappear. The solution is to also set the dc.Style.SelectionBackColor and dc.Style.SelectionForeColor properties. The cell is still selected, just there's no confusion visual changes (and you can't change the checkbox anyway) – winwaed Dec 12 '15 at 16:39
  • @winwaed that suggestion(are you suggeseting having 'disabled' cells be the same grey when selected?), if so, that doesn't sound like a good idea because that would make it unclear what is selected. If you wanted to prevent a 'disabled' cell from being selected then it'd be better to find some way to do it properly(like reverting the selection as soon as it is clicked or something), rather than just changing colours, which is your suggestion. – barlop Mar 20 '16 at 03:27
  • It is a few months ago, but my code is now in production. The problem was we needed to indicate selection. I can't remember the colors off hand, but I'm sure they were different grays to 'disabled' cells. – winwaed Mar 20 '16 at 21:04
18

You can set a particular row or cell to be read-only, so the user cannot change the value. Is that what you mean?

dataGridView1.Rows[0].ReadOnly = true;
dataGridView1.Rows[1].Cells[2].ReadOnly = true;
Blorgbeard
  • 101,031
  • 48
  • 228
  • 272
0

Step 1:

type form load : -
For i = 0 to Datagridview.columns.count -1
   if i <> 1 then //restricted columns, 'i' is Your column index
    Datagridview.Columns(i).ReadOnly = True
   end if
Next

Step 2

type Cellbeginedit
Datagridview.BeginEdit(True)
Tim Hutchison
  • 3,483
  • 9
  • 40
  • 76
Thamis
  • 1