Results 1 to 21 of 21

Thread: Can't Parse textbox.

Threaded View

  1. #1

    Thread Starter
    Lively Member Mugsy323's Avatar
    Join Date
    Oct 2014
    Posts
    112

    Question Can't Parse textbox.

    I'm trying to restrict the input of a text box to allow only numbers (0-9). I intercept "KeyDown" and update Textbox1.Text only if a number is typed:

    (Updated)
    ----------
    Code:
    Public Class Form1
        Dim strPreviousID As String = ""
    
        Private Sub TextBox1_KeyDown(sender As Object, e As KeyEventArgs) Handles Textbox1.KeyDown
            If e.KeyValue > 95 And e.KeyValue < 106 Then    ' Only ASCII values from "0" to "9".
                strPreviousID += Chr(e.KeyValue - 48)            ' ASCII value is Keyboard - 48
            Else
                TextBox1.Text = strPreviousID
            End If
            strPreviousID = TextBox1.Text
        End Sub
    End Class
    ----------

    PROBLEM (Updated): If the very first character is not a number, it STILL appears in the text box. If you type anything other than a number, the box contents are replaced with that one letter.

    For the life of me, I can not figure out how to stop non-numeric values from appearing.

    All "solutions" found online either don't work with VB.Net or are wildly unnecessarily complex.

    So instead of "KeyDown", I tried "TextChanged":

    Code:
    Public Class Form1
        Dim strPreviousID As String = ""
    
        Private Sub Textbox1_TextChanged(sender As Object, e As EventArgs) Handles Textbox1.TextChanged
            If Textbox1.Text.Last.ToString >= "0" And Textbox1.Text.Last.ToString <= "9" Then ' Only "0" thru "9".
                strPreviousID += Textbox1.Text.Last.ToString
            Else
                Textbox1.Text = strPreviousID
            End If
            Textbox1.Text = strPreviousID
        End Sub
    End Class
    This comes with its own set of problem. Numbers work fine, but "If" line throws an exception if anything other than a number is typed.

    I'm stumped. TIA
    Last edited by Mugsy323; Jul 1st, 2021 at 10:27 PM.

Tags for this Thread

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •  



Click Here to Expand Forum to Full Width