簡體   English   中英

從文本框中讀取單個

[英]Reading single from textbox

這是我的Sub:

    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,但它不起作用(請參見圖片)。

為什么?

再次感謝您對我確定是基本問題的任何答案...仍在學習...

在此處輸入圖片說明

您需要告知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

並避免使用昂貴的異常驅動邏輯

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM