Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Disable Cell Highlighting in a datagridview

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

Any thoughts please

like image 600
Ramji Avatar asked Nov 16 '09 22:11

Ramji


4 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();
}
like image 148
Elle H Avatar answered Nov 02 '22 18:11

Elle H


The only way I've found to "disable" highlighting is to set the SelectionBackColor and the SelectionForeColor in the DefaultCellStyle to the same as the BackColor and ForeColor, respectively. You could probably do this programmatically on the form's Load event, but I've also done it in the designer.

Something like this:

Me.DataGridView1.DefaultCellStyle.SelectionBackColor = Me.DataGridView1.DefaultCellStyle.BackColor
Me.DataGridView1.DefaultCellStyle.SelectionForeColor = Me.DataGridView1.DefaultCellStyle.ForeColor
like image 72
jheddings Avatar answered Nov 02 '22 18:11

jheddings


Did a quick websearch to find out how to make a datagridview selection non-selectable & got this (web page) hit.

Calling ClearSelection on SelectionChanged can and does cause a double firing of the SelectionChanged event, at minimum.

The first event is when the cell/row is selected and, of course, the SelectionChanged event is fired. The second firing is when ClearSelection is called as it causes (and logically so!) the selection of the datagridview to (again) changed (to no selection), thus firing SelectionChanged.

If you have more code than simply ClearSelection going on, as such I do, you'll want to suppress this event until after your code is done. Here's an example:

 private void dgvMyControl_SelectionChanged(object sender, EventArgs e)
{
  //suppresss the SelectionChanged event
  this.dgvMyControl.SelectionChanged -= dgvMyControl_SelectionChanged;

  //grab the selectedIndex, if needed, for use in your custom code
  // do your custom code here

  // finally, clear the selection & resume (reenable) the SelectionChanged event 
  this.dgvMyControl.ClearSelection();
  this.dgvMyControl.SelectionChanged += dgvMyControl_SelectionChanged;
}
like image 5
KCromm Avatar answered Nov 02 '22 18:11

KCromm


in vb speak:

Private Sub datagridview1_SelectionChanged(sender As Object, e As EventArgs) Handles datagridview1.SelectionChanged
        datagridview1.ClearSelection()
End Sub
like image 4
Coder22 Avatar answered Nov 02 '22 17:11

Coder22