在鼠标输入时更改单个单元格forecolor?

时间:2016-07-26 20:04:28

标签: .net vb.net winforms datagridview

是否可以在鼠标输入时更改单元格的前景色?我可以在鼠标输入时更改所有单元格前颜色,但我想在鼠标输入时只更改每个单元格的前景色?

以下是如何操作:

Private Sub myGrid_CellMouseEnter(ByVal sender As Object, ByVal e As System.Windows.Forms.DataGridViewCellEventArgs) Handles myGrid.CellMouseEnter
    myGrid.DefaultCellStyle.ForeColor = Color.DarkRed
End Sub

1 个答案:

答案 0 :(得分:2)

您可以处理CellMouseEnterCellMouseLeave并首先检查单元格是否不是标题单元格,然后将单元格样式的前色设置为所需的颜色:

Private Sub myGrid_CellMouseEnter(sender As Object, e As DataGridViewCellEventArgs) _
    Handles myGrid.CellMouseEnter
    If (e.ColumnIndex < 0 OrElse e.RowIndex < 0) Then Return
    Dim cell = myGrid.Rows(e.RowIndex).Cells(e.ColumnIndex)
    cell.Style.ForeColor = Color.Red
End Sub

Private Sub myGrid_CellMouseLeave(sender As Object, e As DataGridViewCellEventArgs) _
    Handles myGrid.CellMouseLeave
    If (e.ColumnIndex < 0 OrElse e.RowIndex < 0) Then Return
    Dim cell = myGrid.Rows(e.RowIndex).Cells(e.ColumnIndex)
    cell.Style.ForeColor = Color.Black
End Sub