Datagridview自定义和格式化 [英] Datagridview customization and formatting

查看:360
本文介绍了Datagridview自定义和格式化的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个datagrid和datatable。 datagrid中的值来自datable。现在,单元格值在 decimal 中,我想将格式更改为2位小数,但这里是我的问题,而不是所有单元格值都是整数,也包含 STRING VALUE N / A



这是我的填充数据的示例datagrid:

 名称| Col1 | Col2 | 
-----------------------------------------
xxx | N / A | N / A |
yyy | 12.1999999 | 23.012355 |
zzz | 0.12366666 | 12.357878 |

我已经尝试过

  datagrid.columns(1).DefaultCellStyle.Format =N2
datagrid.columns(2).DefaultCellStyle.Format =N2
/ pre>

但是单元格值没有改变格式,我知道问题是单元格值包含字符串。还有其他方式可以绕过这个字符串?

解决方案

在一个win表单中,您可以使用单元格格式化事件。根据您的示例,您可以跳过第一列,然后检查您尝试格式化的值是数字还是N / A或任何 - 如果是数字,则格式适当...

  Private Sub YourGrid_CellFormatting(sender As Object,_ $ b $ as As DataGridViewCellFormattingEventArgs)_ 
处理YourGrid.CellFormatting

如果YourGrid.Columns(e.ColumnIndex).Index> 0
如果isnumeric(e.Value)然后
e.CellStyle.Format =N2
如果
结束如果

End Sub


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?

解决方案

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

这篇关于Datagridview自定义和格式化的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆