为什么这段代码突然出现InvalidCastException [英] Why is this code suddenly giving InvalidCastException

查看:77
本文介绍了为什么这段代码突然出现InvalidCastException的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

突然出现以下错误消息 - 我也显示了有问题的代码。它上周工作但现在不行。

欢迎任何指针或解释。

谢谢。



错误信息

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

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

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

推荐答案

目前代码期望货币符号为£。据我所知,如果用户的货币符号是其他任何东西,至少在 mtbx.Text 最初为空的情况下,这会失败。



就个人而言,我不希望在文本字段中使用货币符号,因为IsNumeric会从字符串中删除当前符号。然而,这在货币符号可能改变的情况下引入了可能的错误源。在我看来,使用具有允许元素和特定cultureinfo的TryParse将是更可靠的解决方案。



请参阅 Decimal.TryParse方法(String,NumberStyles,IFormatProvider,Decimal) [ ^ ]
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)[^]


这篇关于为什么这段代码突然出现InvalidCastException的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆