Reputation: 5162
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
Upvotes: 1
Views: 24191
Reputation: 1749
I had the same problem in C# and solved by converting the text to a double first, then formatting the double as a string.
I know this is VB and not C# but I thought I'd share my solution as it came up in my Google results, and might help someone out.
double d;
Double.TryParse(r.Cells[i].Text, out d);
e.Cells[i].Text = String.Format("{0:C0}", d).ToString();
Upvotes: 0
Reputation: 63966
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:
<asp:BoundColumn DataField="YourCurrencyField" DataFormatString="{0:C}" />
Obviously, you still need to make sure that your field is a valid number that can be formatted as a currency.
Upvotes: 2
Reputation: 6406
Try using
e.Row.Cells(i).Text = Convert.ToDecimal(e.Row.Cells(i).Text).ToString("c0")
Instead of
e.Row.Cells(i).Text = Format(e.Row.Cells(i).Text, "c0").ToString()
Upvotes: 4
Reputation: 26386
Move
e.Row.Cells(i).Text = Format(e.Row.Cells(i).Text, "c0").ToString()
into the If function. That line was not checking if it was date column. Probably trying to convert a date to currency
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
Upvotes: 0