【问题标题】:How can I highlight the current cell in a DataGridView when SelectionMode=FullRowSelect当 SelectionMode=FullRowSelect 时,如何突出显示 DataGridView 中的当前单元格
【发布时间】:2008-09-16 15:18:57
【问题描述】:

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

【问题讨论】:

  • Alternate option 我在CurrentCell 上始终显示焦点矩形的位置进行了编码。不是不一样的BackColor,但是效果是一样的。

标签: .net vb.net winforms datagridview


【解决方案1】:

我想出了一个更好的方法,使用 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

【讨论】:

    【解决方案2】:

    对我来说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
    

    【讨论】:

    • 这只是 7 年前接受的答案的副本。当您有足够的代表时,您应该对接受的答案进行投票,而不是重新发布。
    【解决方案3】:

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

    一个例子在MSDN

    【讨论】:

    • 谢谢。但是,据我了解,MSDN 文章似乎建议我应该使用 RowPrePaint 方法。尽管如此,我仍然想不出要使用的正确代码。
    【解决方案4】:

    试试这个,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
    

    【讨论】:

      猜你喜欢
      • 2023-02-17
      • 2018-06-01
      • 1970-01-01
      • 1970-01-01
      • 2016-08-27
      • 2015-08-28
      • 2012-09-17
      • 1970-01-01
      • 2020-08-13
      相关资源
      最近更新 更多