Disable Cell Highlighting in a datagridview

Viewed 93386

How to disable Cell Highlighting in a datagridview, Highlighting should not happen even if I click on the cell.

Any thoughts please

10 Answers

The ForeColor/BackColor kludge wasn't working for me, because I had cells of different colors. So for anyone in the same spot, I found a solution more akin to actually disabling the ability.

Set the SelectionChanged event to call a method that runs ClearSelection

private void datagridview_SelectionChanged(object sender, EventArgs e)
{
    this.datagridview.ClearSelection();
}
Private Sub DGW2_DataBindingComplete(ByVal sender As Object, ByVal e As System.Windows.Forms.DataGridViewBindingCompleteEventArgs) Handles DGW2.DataBindingComplete
    Dim mygrid As DataGridView
    mygrid = CType(sender, DataGridView)
    mygrid.ClearSelection()
End Sub

The answers I saw so far didn't give me exactly what I was looking for, but they showed me the right direction. In my case, after binding to a data source, the DGV selected and highlighted one cell, which I didn't want. I wanted to highlight only if the user selected the complete row.

After a while I found the following solution, which is working fine for me:

private void datagridview_SelectionChanged(object sender, EventArgs e)
{       
    var dgv = (DataGridView)sender;
    if (dgv.SelectedCells.Count == 1)
    {   // hide selection for the single cell
        dgv.DefaultCellStyle.SelectionBackColor = dgv.DefaultCellStyle.BackColor;
        dgv.DefaultCellStyle.SelectionForeColor = dgv.DefaultCellStyle.ForeColor;
    }
    else
    {   // show the selected cells
        dgv.DefaultCellStyle.SelectionBackColor = dgv.RowsDefaultCellStyle.SelectionBackColor;
        dgv.DefaultCellStyle.SelectionForeColor = dgv.RowsDefaultCellStyle.SelectionForeColor;
    };
}

Note: In my example, I have set the properties

MultiSelect = false, ReadOnly = true

because I am using the DGV just to display search results.

<DataGrid ItemsSource="{Binding Credits}" x:Name="Grid"
                          HorizontalAlignment="Left" RowBackground="Transparent">
Related