The following code is my rowdatabound event for my gridview. It works for everything other than the cell text formatting as a currency. In fact the code line where i format the currency
causes the code to err. If i comment out the FormatCurrency line the code works fine. Why does that line a). not format the cell’s text and b). cause the error?
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
As someone else said above, your code will error out if you attempt to format a non-numeric value as a currency and it seems to me that you are not doing that.
Instead, if you want a particular column to be formatted as a currency, use the DataFormatString property of the column as so:
Obviously, you still need to make sure that your field is a valid number that can be formatted as a currency.