簡體   English   中英

在 VB.NET 中,如何讓文本框只允許一個小數點,< 3NUMBERS 之前,只有 1NUMBER 之后?

[英]In VB.NET how do I get a textbox to only allow one decimal point, < 3NUMBERS before it, and only 1NUMBER after it?

正如問題所暗示的那樣,我需要一個文本框來只允許一個小數點,在它之前少於三個數字,在它之后只允許一個數字。

到目前為止,我已經編譯了這段代碼。

Private Sub TextBox14_KeyPress(ByVal sender As Object, ByVal e As System.Windows.Forms.KeyPressEventArgs) Handles TextBox14.KeyPress
    Dim keyChar = e.KeyChar

    If Char.IsControl(keyChar) Then
        'Allow all control characters.
    ElseIf Char.IsDigit(keyChar) OrElse keyChar = "."c Then
        Dim text = Me.TextBox14.Text
        Dim selectionStart = Me.TextBox14.SelectionStart
        Dim selectionLength = Me.TextBox14.SelectionLength

        text = text.Substring(0, selectionStart) & keyChar & text.Substring(selectionStart + selectionLength)

        If Integer.TryParse(text, New Integer) AndAlso text.Length > 3 Then
            'Reject an integer that is longer than 16 digits.
            e.Handled = True
        ElseIf Double.TryParse(text, New Double) AndAlso text.IndexOf("."c) < text.Length - 3 Then
            'Reject a real number with two many decimal places.
            e.Handled = True
        End If
    Else
        'Reject all other characters.
        e.Handled = True
    End If
End Sub

我遇到的最大問題是用戶可以輸入多個小數點,然后基本上我創建的所有規則都消失了。 此外,用戶無法在我希望的情況下在小數點前設置 2 個數字。

用我的頭解決了它。

Private Sub TextBox11_KeyPress(ByVal sender As Object, ByVal e As System.Windows.Forms.KeyPressEventArgs) 處理 TextBox11.KeyPress '允許在銷售價格文本框中輸入的內容 Dim keyChar = e.KeyChar

    If Char.IsControl(keyChar) Then
        'Allow all control characters.
    ElseIf Char.IsDigit(keyChar) OrElse keyChar = "."c Then
        Dim text = Me.TextBox11.Text
        Dim selectionStart = Me.TextBox11.SelectionStart
        Dim selectionLength = Me.TextBox11.SelectionLength

        text = text.Substring(0, selectionStart) & keyChar & text.Substring(selectionStart + selectionLength)
        If TextBox11.Text.Contains("."c) Then
            'Forbids a user from entering in two decimal places
            If keyChar = "."c Then
                e.Handled = True
            ElseIf text.Length - text.IndexOf("."c) > 3 Then
                e.Handled = True
            End If
        Else 'no decimal point currently in textbox
            If text.Length > 5 And keyChar = ("."c) Then 'Allows only a "." to be written 
                e.Handled = False
            ElseIf text.Length > 5 Then ' Numbers before decimal point above 99,999
                e.Handled = True
            End If
        End If
    Else
        'Reject all other characters for this textbox.
        e.Handled = True
    End If
End Sub

暫無
暫無

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

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