Click here to Skip to main content
15,886,362 members
Please Sign up or sign in to vote.
1.00/5 (1 vote)
All of a sudden the following error message is being produced - I've shown the code in question as well. It was working last week but now isn't.
Any pointers or explanations welcomed.
Thanks.

The Error Message
VB
************** Exception Text **************
System.InvalidCastException: Conversion from string "£0.00" to type 'Decimal' is not valid.
   at Microsoft.VisualBasic.CompilerServices.Conversions.ToDecimal(String Value, NumberFormatInfo NumberFormat)
   at Microsoft.VisualBasic.CompilerServices.Conversions.ToDecimal(String Value)
   at GtracsX4.gtac1b.tBox_Validating(Object sender, CancelEventArgs e)


The Code
VB
Private Sub tBox_Validating(ByVal sender As Object, ByVal e As System.ComponentModel.CancelEventArgs) Handles _
      amtInp.Validating, DescInp.Validating, RefInp.Validating
    Dim mtb As String = sender.tag : Dim mtbx As TextBox = sender : Dim ta As Decimal
    If mtb = "dec" Then
        If (String.IsNullOrEmpty(mtbx.Text)) Then mtbx.Text = "0"
        If IsNumeric(mtbx.Text) = False Then
            msgM = "Only NUMBERS allowed.  Please re-enter"
            msg = New gtzMess(1, "", msgM, "OK", "", "", "S")   '   flags = ISQW
            msg.ShowDialog()
            mtbx.Text = 0
            e.Cancel = True
            Exit Sub
        End If
        ta = CDec(mtbx.Text)
        mtbx.Text = "£" & ta.ToString("N2")
        If mtbx.Name = "amtInp" Then tAmt.Text = CDec(mtbx.Text)
    End If
End Sub
Posted

1 solution

Currently the code expects that the currency symbol is £. As far as I can see, if the currency symbol for the user is anything else, this would fail at least in a situation where mtbx.Text initially is empty.

Personally I would prefer not using the currency symbol in the text fields since IsNumeric removes the current symbol from the string. However this introduces a possible error source in situations where the currency symbol may change. In my opinion using TryParse with allowed elements and specific cultureinfo would be more reliable solution.

See Decimal.TryParse Method (String, NumberStyles, IFormatProvider, Decimal)[^]
 
Share this answer
 
v2
Comments
Member 11890082 6-Sep-15 7:02am    
Sorry for delay in getting back. I have discovered one other thing about the code.
It works in Windows 7 but NOT in Windows 10! Have you any idea why that might be?
Wendelius 7-Sep-15 12:19pm    
Sorry, but I haven't yet had the privilege to get to know WIX :) Probably you should open a separate question for that.

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900