'system.invalidcastexception 'conversion from string to type 'double' is not valid.' vb.net

system.invalidcastexception 'conversion from string to type 'double' is not valid.

    ' vb.net
    receiptDetails = lstReceipt.SelectedItem
    Dim newTotalAmount As Double = CDbl(receiptDetails.Remove(0, 94))

    lstReceipt.Items.RemoveAt(lstReceipt.SelectedIndex)
    totalAmount -= newTotalAmount

    txtTotal.Text = totalAmount.ToString("GH₵###,###.00")
    txtDiscount.Text = discountAmount.ToString("GH₵###,###.00")
    txtTaxableAmount.Text = TaxableAmount.ToString("GH₵###,###.00")
    txtVat.Text = taxAmount.ToString("GH₵###,###.00")
    txtPayableAmount.Text = payableAmount.ToString("GH₵###,###.00")

End Sub


Solution 1:[1]

If I had to guess, the code is failing at:

Dim newTotalAmount As Double = CDbl(receiptDetails.Remove(0, 94))

I suggest using TryParse instead of CDbl to verify that the value can be converted to a Double. If the result of TryParse is False, then display the value that attempted to be converted:

Dim massagedValue As String = receiptDetails.Remove(0, 94)
Dim newTotalAmount As Double
If (Double.TryParse(massagedValue, newTotalAmount)) Then
    ' continue business logic ...
Else
    MessageBox.Show($"The following value is not a valid double: {massagedValue}", "Invalid Double", MessageBoxButtons.OK, MessageBoxIcon.Error)
End If

Now when you get the user-friendly error message you can determine why the value is not able to be converted to a double.

My best guess is that you are not removing enough or are removing too much characters from the receiptDetails variable.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 David