0

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?

Chris
  • 8,527
  • 10
  • 34
  • 51
rayncorg
  • 963
  • 4
  • 16
  • 33
  • I tried "N2" and it gave me `1.00`. Try `dgv.columns("dgvcolumnname")` Another thing, I use "D2" for whole numbers = `01` – AdorableVB Feb 14 '14 at 07:08
  • @ AdorableVB I already solved this problem.. **i used if else statement**..anyways thank for the response – rayncorg Feb 14 '14 at 07:13

2 Answers2

1

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
user2543368
  • 54
  • 1
  • 8
0

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

Wolf
  • 6,361
  • 2
  • 28
  • 25