2016-08-04 108 views
1

我有這個問題,看起來很奇怪,我開發一個程序只發送錯誤信息在Windows 8的計算機上,但Windows 7和Windows 10完美工作。VB.NET錯誤DatagridViewCellValueChanged Windows 8

我將在幾行代碼中討論一些錯誤,特別是在事件DataGridViewCellValueChanged中我將一個數字轉換爲硬幣格式,但奇怪的是事件在它們改變之前運行(在我看來) cell的值,我認爲cellvaluechanged事件應該在用戶在單元格中輸入某些內容然後離開該單元時執行,這與CellEndEdit「類似」,但只有當單元格的值發生變化時纔會執行,但在此特定情況下用戶按下指定列中任何單元格中的任何字符而不會丟失單元格的焦點併發送錯誤。

在我的電腦與Windows 7的程序運作良好,並在Windows 10也

這是代碼:

Private Sub GridCatalogo_CellValueChanged(sender As Object, e As System.Windows.Forms.DataGridViewCellEventArgs) Handles GridCatalogo.CellValueChanged 
    If GridCatalogo.Columns(e.ColumnIndex).ToolTipText = "$" Then 
     If IsNothing(GridCatalogo.Item(e.ColumnIndex, e.RowIndex).Value) = False Then 
      Try 
       GridCatalogo.Item(e.ColumnIndex, e.RowIndex).Value = Format(CType(GridCatalogo.Item(e.ColumnIndex, e.RowIndex).Value, Decimal), "$#,##0.00") 
      Catch ex As Exception 
       'MsgBox(ex.Message) 
      End Try 
     End If 
    End If 
End Sub 

我知道,是不是需要一個錯誤消息的圖像,但希望顯示用戶在DataGridView中鍵入的數據。

enter image description here

的消息稱:

從字符串 「$ 8.00」 到 '十進制' 轉換不受支持。

正如你可以在代碼中看到,我不得不處理錯誤停止顯示該信息,所以只能暫時解決這個錯誤,但不明白爲什麼出現這種情況僅在Windows 8

回答

0

此代碼的幫助你調試。在您完成任務時,您希望s爲「$ 8.00」,並且您應該沒有問題。如果錯誤消息顯示了一個您沒有預料到的值,但它在分配後的某個時間位於網格中,那麼您知道您有時間問題。

Private Sub GridCatalogo_CellValueChanged(sender As Object, e As System.Windows.Forms.DataGridViewCellEventArgs) Handles GridCatalogo.CellValueChanged 
    If GridCatalogo.Columns(e.ColumnIndex).ToolTipText = "$" Then 
     If IsNothing(GridCatalogo.Item(e.ColumnIndex, e.RowIndex).Value) = False Then 
      Dim s As String = "not set" 
      Dim d As Decimal = Decimal.MinValue 
      Try 
       s = GridCatalogo.Item(e.ColumnIndex, e.RowIndex).Value 
       d = CType(s, Decimal) 
       GridCatalogo.Item(e.ColumnIndex, e.RowIndex).Value = Format(d, "$#,##0.00") 
      Catch ex As Exception 
       MsgBox(String.Format("s={0}, d={1}, ex.message={2}", s, d, ex.Message)) 
      End Try 
     End If 
    End If 
End Sub 

您的格式方法可能適用,但爲什麼不使用貨幣格式?如果CurrentCulture不起作用,您可以指定它。

Sub Main() 
    Dim currencyString = "$8.00" 

    Dim currencyOPFormat = Format(CType(currencyString, Decimal), "$#,##0.00") 

    Dim currencyDecimal = Decimal.Parse(currencyString, Globalization.NumberStyles.Currency) 
    Dim currencyNewFormat = currencyDecimal.ToString("C", CultureInfo.CurrentCulture) 

    Console.WriteLine("Original: " & currencyOPFormat) 

    Console.WriteLine("Parsed Decimal: " & currencyDecimal) 
    Console.WriteLine("Formatted Decimal: " & currencyNewFormat) 

    Console.ReadLine() 
End Sub 

查看關於貨幣格式:https://msdn.microsoft.com/en-us/library/dwhawy9k(v=vs.110).aspx#CFormatString

+0

謝謝你,即使我不嘗試你的代碼,因爲首先我想更好地瞭解它,但你所提到的我給我的想法來解決這個問題,只有我必須改變這些電腦設置的格式。 – Rchrd