1

I know I can do this:

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

But my DGV cell is already a Double so I would get his value without conversion.

I've tried the below code (but it isn't the right syntax)

Dim Amount As Double = DGVRow.Cells.OfType(Of Double)("Amount").Value
genespos
  • 2,849
  • 4
  • 30
  • 60
  • Since a column/cell needs to be able contain anything, it returns `Object` which means your value is boxed. If you have a datasource, you *can* do much what you are asking: `Dim d = dt.Rows(n).Field(Of Double)("Amount")`. There is still a conversion, just a different kind. Decimal would be a better choice for money type values though – Ňɏssa Pøngjǣrdenlarp Jul 06 '16 at 19:18
  • @Plutonix No. In this case I have no datatable set as source. I chose 'Double' because I have to do calculation which use 'Double' and I don't need extreme precision. Anyway thanks for your precious hints ;) – genespos Jul 07 '16 at 06:36
  • *Especially* if it is money *and* there are calculations, `Decimal` is a better choice. It prevents rounding errors - see http://stackoverflow.com/q/1165761 and http://stackoverflow.com/q/890100 – Ňɏssa Pøngjǣrdenlarp Jul 07 '16 at 13:01

2 Answers2

1

If you sure that cell contains value of type Double then use DirectCast

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

Other way will be working straight with values of bounded DataSource, as @Plutonix explained in the comments

Fabio
  • 28,602
  • 3
  • 26
  • 58
1

If you know that it will always contain a Double, you should use DirectCast

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

These all produce resulting variables of type Double

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

But there are different things going on behind the scenes. DirectCast is the most straightforward.

Check this post Difference between DirectCast() and CType() in VB.NET which details the difference between the conversion methods in VB.net. Also this one VB CStr, CDate, CBool, etc. vs. DirectCast for casting without conversion.

Basically, DirectCast is preferred when you know your Object contains the type you expect, so no conversion is necessary. It will be faster than the other options.

Community
  • 1
  • 1
djv
  • 11,577
  • 7
  • 43
  • 62