CodeGuru Home VC++ / MFC / C++ .NET / C# Visual Basic VB Forums Developer.com
Results 1 to 4 of 4
  1. #1
    Join Date
    Sep 2002
    Posts
    47

    I want to be able to write juste numbers in a textbox

    Hi

    In one of my textbox, the only thing i want that the user can write is a number. Anything else have to be bloc. I thought to return bakcspace if the user write a letter or something else, but i don't know how. Is anybody knows it?

    here's my code

    Dim intKeyAscii As Int32
    intKeyAscii = Asc(e.KeyChar)

    txtDateComptable.Text = ""
    txtNoReference.Text = ""

    If intKeyAscii = 13 Then
    Me.btnTrouver_Click(Me, e)
    ElseIf (intKeyAscii < 48 Or intKeyAscii > 57) then
    'return backspace
    End If

    Thanks
    Alexandre

  2. #2
    Join Date
    Jan 2003
    Location
    Amsterdam, Netherlands
    Posts
    97
    You must implement the KeyPress event on the Textbox.
    There you can control which characters you want to disable in a the Textbox.

    for example, you have a Textbox called Textbox1
    then the following code will only allow 0,1,2,3,4,5,6,7,8,9 and backspace in that textbox.

    Private Sub TextBox1_KeyPress(ByVal sender As Object, ByVal e As System.Windows.Forms.KeyPressEventArgs) Handles TextBox1.KeyPress
    Select Case e.KeyChar
    Case "0"c, "1"c, "2"c, "3"c, "4"c, "5"c, "6"c, "7"c, "8"c, "9"c
    ' All valid character for use in Textbox1
    ' Do Nothing

    Case Microsoft.VisualBasic.ControlChars.Back
    ' BackSpace
    ' Do Nothing

    Case Else
    ' Ignore all others
    e.Handled = True

    End Select
    End Sub
    Last edited by DdH; February 3rd, 2003 at 05:18 PM.

  3. #3
    Join Date
    May 2000
    Location
    New York, NY, USA
    Posts
    2,878
    Private Sub TextBox2_KeyPress(ByVal sender As Object, ByVal e As System.Windows.Forms.KeyPressEventArgs) Handles TextBox2.KeyPress
    If Char.IsDigit(e.KeyChar) Then
    MsgBox("Digit entered")
    End If
    'disable non-digits
    e.Handled = Not Char.IsDigit(e.KeyChar)

    End Sub
    Iouri Boutchkine
    [email protected]

  4. #4
    Join Date
    Feb 2003
    Posts
    44
    You could also try using a Masked Edit Box, which to the user is the exact same thing. Then set the Mask of the Masked Edit Box to only allow a numeric value. I hope this works.

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

Featured