How to disable Cell Highlighting in a datagridview, Highlighting should not happen even if I click on the cell.
Any thoughts please
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();
}
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
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;
}
in vb speak:
Private Sub datagridview1_SelectionChanged(sender As Object, e As EventArgs) Handles datagridview1.SelectionChanged
datagridview1.ClearSelection()
End Sub
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With