这是我的潜艇:
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并且它不起作用(见图)。
为什么?
再次感谢您对我确定的基本问题的任何答案......仍在学习......
答案 0 :(得分: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
并避免昂贵的异常驱动逻辑