DataGridView单元格值的数值比较计算错误



如果温度>=7,我想为datagridview单元格设置背景色。

我使用下面的代码,它的工作很好温度7.01至9.99,但如果温度是10.01及以上,背景颜色不显示。谢谢你的帮助。

Private Sub ReeferDGridview_CellFormatting(ByVal sender As Object, ByVal e As System.Windows.Forms.DataGridViewCellFormattingEventArgs) Handles ReeferDGridview.CellFormatting
    If e.RowIndex >= 0 AndAlso e.ColumnIndex = Me.ReeferDGridview.Columns("Temperature").Index Then
        If e.Value IsNot Nothing Then
            Dim LStatus As String = e.Value.ToString
            Select Case LStatus
                Case Is >= 7
                    Me.ReeferDGridview.Rows(e.RowIndex).DefaultCellStyle.BackColor = Color.Maroon
                    Me.ReeferDGridview.Rows(e.RowIndex).DefaultCellStyle.ForeColor = Color.White
                Case Else
                    Me.ReeferDGridview.Rows(e.RowIndex).DefaultCellStyle.BackColor = Nothing
                    Me.ReeferDGridview.Rows(e.RowIndex).DefaultCellStyle.ForeColor = Color.Black
            End Select
        End If
    End If
End Sub

您的问题在于您将网格中的数值放入String变量中,然后使用该值与Case语句中的数值进行比较。

重要提示:如果您将Option Strict切换为On,您的代码将无法编译,因为它会提醒您正在这样做。

所以当你的代码运行时,它实际上是在比较一个字符串和另一个字符串。>(大于)操作符将按字母顺序或字符代码值顺序(取决于Option Compare设置)进行测试

所以你的代码实际上在做这个

"9.99" > "7" 'evaluates to True
"10" > "7" 'evaluates to False

要解决这个问题,你只需要为LStatus使用数字类型:

Dim LStatus As Single = CSng(e.Value.ToString)

现在可以工作了。我添加了下面的代码:

Dim LStatus As String = e.Value.ToString
Dim number As Double
Double.TryParse(LStatus, number)

最新更新