1 Previous Next 

Numeric textbox for Windows Forms


Often is asked about a numeric textbox. This code does that and checks if as well if there is no numerics are pasted. Be aware you can add to check for decimail points in the way as you wish.
Public Class Form1
    Private Sub TextBox1_KeyPress(sender As Object, e As System.Windows.Forms.KeyPressEventArgsHandles TextBox1.KeyPress
        If Not Char.IsDigit(CChar(e.KeyChar)) AndAlso Not {ControlChars.Back}.Contains(e.KeyChar) Then
            e.Handled = True
        End If
    End Sub
    'For paste protection
    Private Sub TextBox1_Leave(sender As Object, e As EventArgsHandles TextBox1.Leave
        For i = 0 To TextBox1.Text.Length - 1
            Dim x As Char = CChar(TextBox1.Text(i))
            If Not Char.IsDigit(CChar(TextBox1.Text(i))) Then
                MessageBox.Show("TextBox contains not allowed characters")
                TextBox1.Focus()
            End If
        Next
    End Sub
End Class



1 Previous Next