How to restrict character from textbox?

I have a program that use to input currency, but i really don't know how to restrict ascii character in the textbox, all i want is number are to be inputted in the textbox.

Can u help me please:(



Answer this question

How to restrict character from textbox?

  • latesh

    Thanks;)


  • Peter Gadsby

    You can use a masked textbox, or you can handle the key pressed event and write code like this:

    private void OnNumericKeyPress(object sender, KeyPressEventArgs e)

    {

    TextBox tb = sender as TextBox;

    e.Handled = !(Char.IsControl(e.KeyChar) ||

    Char.IsNumber(e.KeyChar) ||

    (e.KeyChar == '.' && !tb.Text.Contains(".")));

    }

    Sorry, that's C#, but all you need to do is use Char.IsControl and Char.IsDigit to check if you want to set e.HAndled. If e.Handled is true, the key press is ignored.



  • Tinman

    You should set e.Handled to True, you should NOT reset the e.KeyChar as an alternative.



  • AndrewLittlejohn

    hi,

    at the top of this forum there is a FAQ thread which has a post about restrict textbox to accept numbers only the links has currency also

    hope this helps



  • CRathjen-MSFT

    hi,

    revised code using e.handled

    Private Sub txtTel_KeyPress(ByVal sender As System.Object, ByVal e As System.Windows.Forms.KeyPressEventArgs) Handles txtTel.KeyPress

    If Char.IsLetter(e.KeyChar) Or Char.IsSymbol(e.KeyChar) Or Char.IsPunctuation(e.KeyChar) Then

    MsgBox("Only Numeric input", MsgBoxStyle.Information, "Invalid From Value")

    'e.KeyChar = ChrW(0)

    e.Handled = True

    End If

    End Sub

    ron


  • panaconsultas

    Hi,

    This is how I code this in VB:

    Private Sub txtTel_KeyPress(ByVal sender As System.Object, ByVal e As System.Windows.Forms.KeyPressEventArgs) Handles txtTel.KeyPress

    If Char.IsLetter(e.KeyChar) Or Char.IsSymbol(e.KeyChar) Or Char.IsPunctuation(e.KeyChar) Then

    MsgBox("Only Numeric input", MsgBoxStyle.Information, "Invalid From Value")

    e.KeyChar = ChrW(0)

    End If

    End Sub

    Hope it helps

    ron


  • How to restrict character from textbox?