numeric charaters only in textfield

  • 19 years ago

    this is my vb program. I want to be able to write only numeric charaters in
    the textfield. If I do enter a alphanumeric charater I want either a error
    message to open or nothing to happen at all. I already have able to get numeric charaters but every time I enter a alphanumeric charater it gives a run time error. I dont a run time error to come. I want message box to come up.


    Private Sub Addbut_Click()
    Dim tnum1 As Integer
    Dim tnum2 As Integer
    Dim tnum3 As Integer


    tnum1 = CInt(Text1.Text)
    tnum2 = CInt(Text2.Text)
    tnum3 = CInt(Text3.Text)


    tnum3 = CInt(Text1.Text) + CInt(Text2.Text)


    End Sub


    Private Sub Text1_Change()
    Dim Num1 As String
    Dim num As Integer


    'num = CInt(Text1.Text)


    If num = CInt(Text1.Text) Then
    MsgBox "error"
    End If



    End Sub
    Function characters(topchar As String) As Data
    Dim alpha As Long
    alpha = "1"
    topchar = Chr(alpha)


    End Function




    Private Sub Text2_Change()
    Dim Num1 As String
    Dim num As Integer


    num = CInt(Text2.Text)
    End Sub


    Private Sub Text3_Change()
    Dim Num1 As String
    Dim num As Integer



    'num = CInt(Text3.Text)
    End Sub


  • 19 years ago

    I found your post kind of confusing, but I think I understood it.  I believe you want it so you can only enter numeric characters into the textbox.  I threw this together really quick.  It checks to see what key you pressed.  If you pressed a number or TAB or backspace it lets it go through, but if you press anything else it ignores it.


    Private Sub Text1_KeyPress(KeyAscii As Integer)
    If Not (IsNumeric(Chr(KeyAscii))) And KeyAscii <> 8 And _
    KeyAscii <> 9 Then
       KeyAscii = 0
       MsgBox "Please enter only numeric characters."
    End If
    End Sub


    There's probably a better way to do this, or characters I missed, but that might help you on your way.

  • 19 years ago

    You might as well just do this:


    Private Sub Text1_KeyPress(KeyAscii As Integer)
    If KeyAscii < 48 Or KeyAscii > 57 Then KeyAscii = 0
    End Sub


    That will make it so that if they try and type in something other than a number, nothing will happen.

Post a reply

Enter your message below

Sign in or Join us (it's free).

Contribute

Why not write for us? Or you could submit an event or a user group in your area. Alternatively just tell us what you think!

Our tools

We've got automatic conversion tools to convert C# to VB.NET, VB.NET to C#. Also you can compress javascript and compress css and generate sql connection strings.

“The difference between theory and practice is smaller in theory than in practice.”