簡體   English   中英

僅在文本框中輸入數字和單位等級(VB.Net)

[英]Input Numbers and Unit Grades Only at Textbox (VB.Net)

嗨,我只是想輸入1到5作為文本框上的單位成績,我使用以下代碼:

Private Sub TextBox16_TextChanged(sender As Object, e As EventArgs) Handles TextBox16.TextChanged
    If TextBox16.Text >= 5 Then
        TextBox16.clear()
        MsgBox("Unit Grades Only From 1 to 5")

    End If
End Sub

結束班

錯誤出現:

Microsoft.VisualBasic.dll中發生了未處理的“System.InvalidCastException”類型異常

附加信息:從字符串“”到類型“ Double”的轉換無效。

如果您打算為此使用文本框,則以下代碼應防止在文本框中使用1到5之外的任何內容。 我使用的文本框命名為txtUnitGrade更好。

Private _sLastValidValue As String = String.Empty
Private _bIgnoreChange As Boolean = False

Private Sub txtUnitGrade_TextChanged(sender As Object, e As EventArgs) Handles txtUnitGrade.TextChanged

If Not _bIgnoreChange Then
    If txtUnitGrade.Text = String.Empty Then
        _sLastValidValue = String.Empty
    Else
        If Not IsNumeric(txtUnitGrade.Text) Then
            SetValueToLast()
        Else
            Dim iParsedValue As Integer = Integer.MinValue
            If Not (Integer.TryParse(txtUnitGrade.Text, iParsedValue)) OrElse iParsedValue < 0 OrElse iParsedValue > 5 Then
                SetValueToLast()
            Else
                _sLastValidValue = txtUnitGrade.Text
            End If
        End If
    End If
End If
End Sub

Private Sub SetValueToLast()
    Beep() 'you could add some other audible or visual cue that an block occured
    _bIgnoreChange = True
    txtUnitGrade.Text = _sLastValidValue
    txtUnitGrade.SelectionStart = txtUnitGrade.Text.Length
    _bIgnoreChange = False
End Sub

好了,您有兩種方法可以做到這一點:

防止輸入
在這種情況下,您將拒絕用戶鍵入其他字符。 因此編寫此代碼:

Private Sub TextBox16_KeyPress(sender As Object, e As KeyPressEventArgs) Handles TextBox16.KeyPress
'Deny user from entering more than one charecter
    TextBox1.MaxLength = 1
    Select Case e.KeyChar
        Case "1", "2", "3", "4", "5" ,vbBack 'vbBack is backspace
            'You can enter any number that you whant
            e.Handled = False
        Case Else
            'Ignore the key
            e.Handled = True
            'Play a Beep sound.
            Beep()
        End Select
End Sub

要么

用TextChanged檢查
在您的方法中輸入:

Dim textbox_val As Integer
'The user may enter alphabetical characters
Try
    textbox_val = Convert.ToInt32(TextBox1.Text)
Catch ex As Exception
    MsgBox("Unit Grades Only From 1 to 5")
    Exit Sub
End Try
If textbox_val >= 5 Then
    TextBox1.Clear()
    MsgBox("Unit Grades Only From 1 to 5")
End If

暫無
暫無

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

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