Only accept digits for textbox

前端 未结 8 930
小鲜肉
小鲜肉 2020-12-10 16:13

I found this code for making my textbox only accept numbers.

Private Sub TextBox1_KeyPress(ByVal sender As System.Object, ByVal e As System.Windows.Forms.Key         


        
相关标签:
8条回答
  • 2020-12-10 16:53

    voldemort

    i develop your first code to allow the user to delete too.

    Here is the code :

    Dim BACKSPACE As Boolean
    
    Private Sub TextBox1_KeyDown(ByVal sender As Object, ByVal e As System.Windows.Forms.KeyEventArgs) Handles TextBox1.KeyDown
        If e.KeyCode = Keys.Back Then
            BACKSPACE = True
        Else
            BACKSPACE = False
        End If
    End Sub
    
    Private Sub TextBox1_KeyPress(ByVal sender As Object, ByVal e As System.Windows.Forms.KeyPressEventArgs) Handles TextBox1.KeyPress
        If BACKSPACE = False Then
            Dim allowedChars As String = "0123456789"
            If allowedChars.IndexOf(e.KeyChar) = -1 Then
                e.Handled = True
            End If
        End If
    End Sub
    

    I Hope My Code Was Useful To You :)

    0 讨论(0)
  • 2020-12-10 17:01
     Private Sub txtValue_KeyPress(ByVal sender As System.Object, ByVal e As System.Windows.Forms.KeyPressEventArgs) Handles txtValue.KeyPress
        Dim allowedChars As String = "."
        'If allowedChars.IndexOf(e.KeyChar) = -1 Then
        '    ' Invalid Character
        '    e.Handled = True
        'End If
        'If (e.KeyChar = Microsoft.VisualBasic.Chr(8)) Then
        '    e.Handled = True
        'End If
        If Char.IsDigit(e.KeyChar) = False And Char.IsControl(e.KeyChar) = False And allowedChars.IndexOf(e.KeyChar) = -1 Then
            e.Handled = True
        End If
    End Sub
    
    0 讨论(0)
提交回复
热议问题