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

有帮助吗?

解决方案

我找到了一种更好的方法来做到这一点,使用 CellFormatting 事件:

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 成功了。我有一组可以编辑的列(我使其以不同的颜色显示),这是我使用的代码:

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

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

一个例子在这里 微软软件定义网络

试试这个 OnMouseMove 方法:

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
许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top