2016-07-06 55 views
1

我知道我能做到这一点:语法提取的DataGridViewCell值,无需转换

Dim Amount As Double = CDbl(DGVRow.Cells("Amount").Value) 

但我DGV细胞已经是Double所以我会得到他的价值,无需转换。

我尝试了下面的代码(但它是不正确的语法)

Dim Amount As Double = DGVRow.Cells.OfType(Of Double)("Amount").Value 
+0

由于列/单元格需要能够包含任何内容,因此它会返回“对象”,这意味着您的值被装箱。如果你有一个数据源,你*可以*做很多你问的问题:Dim d = dt.Rows(n).Field(Of Double)(“Amount”)'。还有一种转换,只是一种不同的类型。尽管 – Plutonix

+0

@Plutonix号码对于金额类型值来说十进制是更好的选择。在这种情况下,我没有将数据集设置为源。我选择'双',因为我必须做计算,使用'双',我不需要极端的精度。无论如何感谢您宝贵的提示;) – genespos

+0

*特别是*如果它是金钱*和*有计算,'十进制'是一个更好的选择。它可以防止舍入错误 - 请参阅http://stackoverflow.com/q/1165761和http://stackoverflow.com/q/890100 – Plutonix

回答

1

如果您知道它将始终包含Double,那么您将乌尔德使用DirectCast

Dim Amount As Double = DirectCast(DGVRow.Cells("Amount").Value, Double) 

这些都产生结果类型的变量双

Dim value As Object 
value = 1.23# 
Dim resultDC = DirectCast(value, Double) 
Dim resultCT = CType(value, Double) 
Dim resultCDBL = CDbl(value) 

但也有不同的东西去幕后。 DirectCast是最直接的。

查看该帖子Difference between DirectCast() and CType() in VB.NET详细介绍了VB.net中转换方法的区别。也是这一个VB CStr, CDate, CBool, etc. vs. DirectCast for casting without conversion

基本上,当您知道您的Object包含您期望的类型时,首选DirectCast,因此不需要转换。它会比其他选项更快。

1

如果您确信细胞含有Double类型的值,然后利用DirectCast

Dim Amount As Double = DirectCast(DGVRow.Cells("Amount").Value, Double) 

其他方式将直接与有界数据源的值一起工作,如@Plutonix在注释中所述

相关问题