Reputation: 993
I have a datagrid and a datatable . Values in datagrid came from datable. Now the cell values is in decimal
and I want to change the format to 2 decimal places but here's my problem not all cell values is integer also it contain STRING VALUE
like N/A
.
Here's my sample datagrid filled with data:
Name | Col1 | Col2 |
-----------------------------------------
xxx | N/A | N/A |
yyy | 12.1999999 | 23.012355 |
zzz | 0.12366666 | 12.357878 |
I already tried
datagrid.columns(1).DefaultCellStyle.Format = "N2"
datagrid.columns(2).DefaultCellStyle.Format = "N2"
but the cell values didn't change the format, I know the problem there is the cell value contain string. There is other way to bypass that string?
Upvotes: 0
Views: 4403
Reputation: 54
In a win form you can use the cell formatting event. Based on your example you could skip the first column and then check to see if the value you are trying to format is numeric or "N/A" or whatever - then format appropriately if it is a number ...
Private Sub YourGrid_CellFormatting(sender As Object, _
e As DataGridViewCellFormattingEventArgs) _
Handles YourGrid.CellFormatting
If YourGrid.Columns(e.ColumnIndex).Index > 0
If isnumeric(e.Value) Then
e.CellStyle.Format = "N2"
End If
End if
End Sub
Upvotes: 1
Reputation: 6499
I think you can format your data before set it to grid datasource or you can format display when binding your data
if you working on asp.net you can try event onrowdatabound
void CustomersGridView_RowDataBound(Object sender, GridViewRowEventArgs e)
{
if(e.Row.RowType == DataControlRowType.DataRow)
{
// Display the company name in italics.
if(your condition)
e.Row.Cells[1].Text = "<i>" + e.Row.Cells[1].Text + "</i>";
}
if you using win form i think similar, can format in event or format when you get result from data or anywhere
Upvotes: 0