1

我有这个看起来很奇怪的问题,我开发了一个程序,它只在装有 Windows 8 的计算机上发送错误消息,但 Windows 7 和 Windows 10 运行良好。

我将在几行代码中讨论一下错误,特别是在DataGridViewCellValueChanged我将数字转换为硬币格式的情况下,但奇怪的是事件在更改单元格的值之前运行(在我看来)我认为当用户在单元格中键入内容然后从该单元格中键入内容时应该执行 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 中键入的数据。

在此处输入图像描述

消息说:

不支持从字符串“$8.00”到“十进制”的转换。

正如您在代码中看到的那样,我必须处理错误以停止显示消息,所以只能暂时修复错误但不明白为什么只会在 Windows 8 中发生这种情况

4

1 回答 1

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

于 2016-08-04T18:35:09.820 回答