格式化为 C2 格式时如何将值传递给 DGV Cell

How to pass a value to DGV Cell when its formatted to C2 format

我正在努力寻找这个问题的具体答案,因此我自己问了...

我有一个 DataGridView,其列应用了以下格式:

DGV.Columns(3).DefaultCellStyle.Format = "C2"

在表单上有一个文本框,用户可以在其中输入一个数字,然后将该值输入到 DGV 中的一个单元格中:

For Each dr As DataGridViewRow In DGV.Rows
    dr.Cells("ColumnHeader").Value = TextBox.Text
Next

在执行上述代码之前,此事件发生在 TextBox 上以格式化其值:

Private Sub TextBox_Leave(sender As Object, e As EventArgs) Handles TextBox.Leave
    TextBox.Text = FormatCurrency(TextBox.Text)
End Sub

TextBox 中的文本正确显示为货币,但是当执行将其放入 DGV 单元格的代码时,它失败并指出值的格式不正确。

DGV.Columns(3).DefaultCellStyle.Format = "C2" 的格式是否与 FormatCurrency(TextBox.Text) 不同?

完全错了。 “C2”是一个数字格式字符串,所以它只适用于数字。包含数字字符的 String 不是数字,包含货币文本的 String 绝对不是。您需要从 TextBox 获取 String,将其转化为一个数字(对于货币值可能是 Decimal),然后将该数字加载到网格中。网格将该数字连同所有数据一起转换为要显示的文本,并将使用您的格式字符串来执行此操作:

dr.Cells("ColumnHeader").Value = CDec(TextBox.Text)

您大概会在此阶段验证用户输入,因此 CDec 不可能抛出异常。

如果目的是在网格和 TextBox 中显示格式化为货币的数据,那么您应该摆脱 Leave 事件处理程序并处理 ValidatingValidated 个事件。第一个将验证输入以确保它是数字,第二个将进行格式化:

Private Sub TextBox1_Validating(sender As Object, e As CancelEventArgs) Handles TextBox1.Validating
    If Not Decimal.TryParse(TextBox1.Text, NumberStyles.Currency, Nothing, Nothing) Then
        'Don't let the control lose focus when it contains invalid data.
        e.Cancel = True
    End If
End Sub

Private Sub TextBox1_Validated(sender As Object, e As EventArgs) Handles TextBox1.Validated
    TextBox1.Text = Decimal.Parse(TextBox1.Text, NumberStyles.Currency).ToString("C2")
End Sub

该代码将允许用户输入或不输入货币符号,但一旦失去焦点,它将确保格式为带两位小数的货币。然后,您需要在复制到网格时允许格式化:

dr.Cells("ColumnHeader").Value = Decimal.Parse(TextBox1.Text, NumberStyles.Currency)