Datagridview customization and formatting

拜拜、爱过 提交于 2020-01-24 00:46:11

问题


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?


回答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



回答2:


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



来源:https://stackoverflow.com/questions/18866889/datagridview-customization-and-formatting

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!