Question

I have an editable DataGridView with SelectionMode set to FullRowSelect (so the whole row is highlighted when the user clicks on any cell). However I would like the cell that currently has focus to be highlighted with a different back color (so the user can clearly see what cell they are about to edit). How can I do this (I do not want to change the SelectionMode)?

Was it helpful?

Solution

I figured out a better way of doing this, using the CellFormatting event:

Private Sub uxContacts_CellFormatting(ByVal sender As Object, ByVal e As System.Windows.Forms.DataGridViewCellFormattingEventArgs) Handles uxContacts.CellFormatting
    If uxContacts.CurrentCell IsNot Nothing Then
        If e.RowIndex = uxContacts.CurrentCell.RowIndex And e.ColumnIndex = uxContacts.CurrentCell.ColumnIndex Then
            e.CellStyle.SelectionBackColor = Color.SteelBlue
        Else
            e.CellStyle.SelectionBackColor = uxContacts.DefaultCellStyle.SelectionBackColor
        End If
    End If
End Sub

OTHER TIPS

For me CellFormatting does the Trick. I have a set of columns that one can Edit (that I made to appear in a different color) and this is the code I used:

Private Sub Util_CellFormatting(ByVal Sender As Object, ByVal e As System.Windows.Forms.DataGridViewCellFormattingEventArgs) Handles dgvUtil.CellFormatting
    If dgvUtil.CurrentCell IsNot Nothing Then
        If e.RowIndex = dgvUtil.CurrentCell.RowIndex And e.ColumnIndex = dgvUtil.CurrentCell.ColumnIndex And (dgvUtil.CurrentCell.ColumnIndex = 10 Or dgvUtil.CurrentCell.ColumnIndex = 11 Or dgvUtil.CurrentCell.ColumnIndex = 13) Then
            e.CellStyle.SelectionBackColor = Color.SteelBlue
        Else
            e.CellStyle.SelectionBackColor = dgvUtil.DefaultCellStyle.SelectionBackColor
        End If
    End If
End Sub

You want to use the DataGridView RowPostPaint method. Let the framework draw the row, and afterwards go back and color in the cell you're interested in.

An example is here at MSDN

Try this, the OnMouseMove method:

Private Sub DataGridView1_CellMouseMove(sender As Object, e As System.Windows.Forms.DataGridViewCellMouseEventArgs) Handles DataGridView1.CellMouseMove
    If e.RowIndex >= 0 Then
        DataGridView1.Rows(e.RowIndex).Cells(e.ColumnIndex).Style.SelectionBackColor = Color.Red
    End If
End Sub

Private Sub DataGridView1_CellMouseLeave(sender As Object, e As System.Windows.Forms.DataGridViewCellEventArgs) Handles DataGridView1.CellMouseLeave
    If e.RowIndex >= 0 Then
        DataGridView1.Rows(e.RowIndex).Cells(e.ColumnIndex).Style.SelectionBackColor = DataGridView1.DefaultCellStyle.SelectionBackColor
    End If
End Sub
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top