【问题标题】:Reading single from textbox从文本框中读取单曲
【发布时间】:2015-07-17 17:29:24
【问题描述】:

这是我的潜艇:

    Protected Sub PrincipleTextBox_TextChanged(sender As Object, e As EventArgs)
    Try
        principle = Single.Parse(PrincipleTextBox.Text)
        PrincipleTextBox.BackColor = Drawing.Color.Empty
        ResultLabel.ForeColor = Drawing.Color.Black
        ResultLabel.Text = "hi"
    Catch ex As Exception
        PrincipleTextBox.BackColor = Drawing.Color.Pink
        ResultLabel.ForeColor = Drawing.Color.Red
        ResultLabel.Text = "Money values only for principle"
    End Try
    PrincipleTextBox.Text = FormatCurrency(principle)
End Sub

如果文本框中不是实数,我想阅读实数以了解原理和一些基本警告。所以,我输入 225 并不起作用(见图)。

为什么?

再次感谢您对我确定是一个基本问题的任何答案...仍在学习...

【问题讨论】:

    标签: .net vba textbox


    【解决方案1】:

    您需要通知 Parse 方法有关特定文化的货币符号的存在

    Dim info = New CultureInfo("en-US")
    Dim principle = Single.Parse(PrincipleTextBox.Text, NumberStyles.Currency, info)
    

    但是,作为用户输入的输入,您应该以更具防御性的态度来处理转换问题。如果您的用户设法编写无法转换为数字的内容,那么最好使用

     Dim principle as Single
     Dim info = New CultureInfo("en-US")
     If Not Single.TryParse(PrincipleTextBox.Text, NumberStyles.Currency, info, principle) Then
         ' Code for invalid number input instead of catching the exception
          PrincipleTextBox.BackColor = Drawing.Color.Pink
          ResultLabel.ForeColor = Drawing.Color.Red
          ResultLabel.Text = "Money values only for principle"
     Else
        PrincipleTextBox.BackColor = Drawing.Color.Empty
        ResultLabel.ForeColor = Drawing.Color.Black
        ResultLabel.Text = "hi"
    End If
    

    并避免昂贵的异常驱动逻辑

    【讨论】:

    • 大部分非常有用的信息,我什至没有想到有人输入货币符号。不,我只有一个简单的 225 作为输入就得到了我的错误。不过,TryParse 看起来很有希望。让我看看我能看到什么……谢谢!
    • 删除异常处理程序并让代码崩溃并显示有意义的错误消息应该是下一步尝试了解正在发生的事情以及为什么 Parse 调用无法转换简单的有效数字文本
    • 我已经发现 .Text 没有改变,所以当我输入 '225 enter' 时,程序正在尝试解析 '$0.00' 并且失败(我还没有尝试过 CultureInfo )。我不确定为什么 Enter 键没有改变文本字段。
    • 您是否在 Page_Load 事件中将 PrincipleTextBox 设置为零?您是否在 Page_Load 事件中测试 Postback 标志?请记住,Page_Load 事件在每个服务器端事件之前触发,而不仅仅是在您第一次加载页面时。
    • 我现在明白了。我注释掉了我的 Page_Load 子,它开始正常工作。现在我需要: - 了解有关 Page_Load 的更多信息 - 决定是否有必要 感谢一百万!
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2012-08-24
    • 2016-12-16
    • 1970-01-01
    • 2012-09-27
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多