genespos genespos - 1 year ago 41 Question

Syntax to extract DataGridViewCell value without conversion

I know I can do this:

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

But my DGV cell is already a
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

Answer Source

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 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.