Search code examples
c#maskedtextbox

How to only allow the numbers ,backspace key and hypen key to be pressed on textbox


I made a textbox to to insert a phone number . I only want numbers, delete button and hyphen key to be pressed. I used following code : It works for delete button and numbers , what shoud I do for hyphen?

private void ContactNumTextBox_KeyPress(object sender, KeyPressEventArgs e)
{
    const char Hyphen = (char)2d;
    const char Delete = (char)8;
    if (char.IsNumber(e.KeyChar) && e.KeyChar != Hyphen && e.KeyChar!= Delete)
        e.Handled = true; 
}

Solution

  • When using hex numbers, you must prefix the number with 0x. Your code currently compiles due to the coincidence that d specifies the number is a double. The following code will correctly detect hyphens:

    private void ContactNumTextBox_KeyPress(object sender, KeyPressEventArgs e)
    {
        const char hyphen = (char)0x2D;
        const char delete = (char)0x08;
        if (!char.IsNumber(e.KeyChar) && e.KeyChar != hyphen && e.KeyChar!= delete)
            e.Handled = true; 
    }