簡體   English   中英

DataGridView單元格值的數值比較評估不正確

[英]Numeric Comparison of DataGridView Cell Value Evaluates Incorrectly

如果溫度> = 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 ,則您的代碼將無法編譯,因為它會提醒您執行此操作的事實。

因此,當您的代碼運行時,它實際上是在將一個字符串與另一個字符串進行比較。 >(大於)運算符將按字母順序或字符代碼值順序進行測試(取決於“選項比較”設置)

所以您的代碼實際上正在這樣做

"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)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM