当前位置:首页> 正文

关于.net:当SelectionMode = FullRowSelect时,如何突出显示DataGridView中的当前单元格

关于.net:当SelectionMode = FullRowSelect时,如何突出显示DataGridView中的当前单元格

How can I highlight the current cell in a DataGridView when SelectionMode=FullRowSelect

我有一个可编辑的DataGridView,其中SelectionMode设置为FullRowSelect(因此,当用户单击任何单元格时,整个行将突出显示)。 但是,我希望以不同的背景色突出显示当前具有焦点的单元格(以便用户可以清楚地看到他们将要编辑的单元格)。 我该怎么做(我不想更改SelectionMode)?


我使用CellFormatting事件找到了一种更好的方法:

1
2
3
4
5
6
7
8
9
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

对我来说,CellFormatting会执行技巧。 我有一组可以编辑的列(使它们以其他颜色显示),这是我使用的代码:

1
2
3
4
5
6
7
8
9
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


尝试使用OnMouseMove方法:

1
2
3
4
5
6
7
8
9
10
11
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

您要使用DataGridView RowPostPaint方法。 让框架绘制行,然后返回并在感兴趣的单元格中着色。

一个例子在这里MSDN


展开全文阅读

相关内容