1

以下代码是我的 gridview 的 rowdatabound 事件。它适用于除单元格文本格式作为货币之外的所有内容。事实上,我格式化货币的代码行会导致代码出错。如果我注释掉 FormatCurrency 行,则代码可以正常工作。为什么那行a)。不格式化单元格的文本和 b)。导致错误?

    Protected Sub gvDataRetrieval_RowDataBound(sender As Object, e As GridViewRowEventArgs) Handles gvDataRetrieval.RowDataBound
    If e.Row.RowType = DataControlRowType.DataRow Then
        Dim dateindex As Integer = GetColumnIndexByHeaderText(gvDataRetrieval, "date")
        e.Row.Cells(dateindex).Text = Split(e.Row.Cells(dateindex).Text, " ")(0)
        For i As Integer = 0 To e.Row.Cells.Count - 1
            e.Row.Cells(i).Font.Size = 10
            e.Row.Cells(i).HorizontalAlign = HorizontalAlign.Center
            If i > dateindex Then
                If Convert.ToDecimal(e.Row.Cells(i).Text) < 0 Then
                    e.Row.Cells(i).ForeColor = Drawing.Color.Red
                Else
                    e.Row.Cells(i).ForeColor = Drawing.Color.Black
                End If
            End If
            e.Row.Cells(i).Text = FormatCurrency(e.Row.Cells(i).Text, 0)
        Next
    End If

End Sub
4

4 回答 4

4

尝试使用

e.Row.Cells(i).Text = Convert.ToDecimal(e.Row.Cells(i).Text).ToString("c0")

代替

e.Row.Cells(i).Text = Format(e.Row.Cells(i).Text, "c0").ToString()
于 2012-06-04T00:13:40.710 回答
2

正如上面其他人所说,如果您尝试将非数字值格式化为货币,您的代码将出错,在我看来,您没有这样做。

相反,如果您希望将特定列格式化为货币,请使用该列的 DataFormatString 属性,如下所示:

<asp:BoundColumn DataField="YourCurrencyField" DataFormatString="{0:C}" />

显然,您仍然需要确保您的字段是可以格式化为货币的有效数字。

于 2012-06-04T00:20:18.703 回答
0

移动

 e.Row.Cells(i).Text = Format(e.Row.Cells(i).Text, "c0").ToString()

进入 If 函数。该行没有检查它是否是日期列。可能试图将日期转换为货币

        If i > dateindex Then
            If Convert.ToDecimal(e.Row.Cells(i).Text) < 0 Then
                e.Row.Cells(i).ForeColor = Drawing.Color.Red
            Else
                e.Row.Cells(i).ForeColor = Drawing.Color.Black
            End If
            e.Row.Cells(i).Text = Format(e.Row.Cells(i).Text, "c0").ToString()
        End If
于 2012-06-03T23:59:36.383 回答
0

我在 C# 中遇到了同样的问题,并通过先将文本转换为双精度,然后将双精度格式化为字符串来解决。

我知道这是 VB 而不是 C#,但我想我会分享我的解决方案,因为它出现在我的 Google 结果中,并且可能会帮助某人。

double d;
Double.TryParse(r.Cells[i].Text, out d);
e.Cells[i].Text = String.Format("{0:C0}", d).ToString();
于 2014-11-13T06:03:53.853 回答