Type conversion going wrong

Asked

Viewed 76 times

1

I have a data conversion problem when going through For Each, accuses the item "vl_maodeobra" cannot be converted from String to type Integer. The problem is that no matter what conversion I try to make of the same error, only changing the message, for example: can not be converted from String for Double or to Decimal.

The item "vl_maodeobra" returns numbers with comma, decimals and the Query below returns the data correctly. The error only appears when you pass the line vl_mo_total += mObra.Rows("vl_maodeobra").ToString().

I’m trying to add the value of labor to each line that returns from query.

SB = New System.Text.StringBuilder
SB.Append(" Select a.vl_maodeobra ")
SB.Append(" from garantia a ")
SB.Append(" where a.dt_exclusao is null ")
SB.Append(" and a.dt_inclusao >= to_date('01/01/2013', 'dd/mm/yyyy') ")
SB.Append(" and a.cd_laudo = 21 ")
SB.Append(" and cd_tipo_garantia <> 'C' ")
SB.Append(" and a.vl_total > 0 ")
SB.Append(" and a.nu_lote = " & LO.ToString & " ")
SB.Append(" and a.cd_concessionario = 5 ")
Dim mObra As DataTable = DB.CreateDataTable(SB.ToString)



If mObra.Rows.Count >= 1 Then
   Dim vl_mo_total As Double = 0
   For Each currow2 As DataRow In mObra.Rows
      vl_mo_total += mObra.Rows("vl_maodeobra").ToString()
   Next

1 answer

1


Try this:

If mObra.Rows.Count >= 1 Then
   Dim vl_mo_total As Double = 0
   For Each currow2 As DataRow In mObra.Rows
      vl_mo_total += Convert.ToDouble(currow2("vl_maodeobra")) //esta é uma forma simplificada
   Next
End If

I put in the Github for future reference.

It may be that it needs some adaptation in the conversion depending on what you need and how this data is returned.

But the question still remains, do you work with monetary value with the type Double? I hope it was just a test.

  • For now I’m just testing, but as soon as it works and the customer approves I’ll go up to production. That way it worked, but you don’t recommend the Double type for monetary value ? Because in some cases it will exceed 100 results and each result will have a different value, and the value can be very high.

  • 1

    Then use Decimal. Double is prohibitive for monetary values, it has precision problems. It works well for scientific calculations, but it’s bad for financial values that can’t have penny differences. see: http://answall.com/a/38140/101 Read more. Your code can cause financial and even legal problems for the company.

  • I will switch to decimal. Thank you very much !

  • I may be wrong, but I think that if in the database this column is not mandatory it is necessary to test if the value is null (Dbnull).

Browser other questions tagged

You are not signed in. Login or sign up in order to post.