5

Possible Duplicate:
How do I make a textbox that only accepts numbers?

I have a phone number that I wish to store as a string.

I read this in using

txtHomePhone.Text

What I think I need is some kind of is numeric but can't get it working

if (txtHomePhone.Text == //something.IsNumeric)
{
    //Display error
}
else
{
    //Carry on with the rest of program ie. Add Phone number to program.
}

What is the best way to allow only numeric values to be entered?

Community
  • 1
  • 1
Wizard
  • 1,142
  • 3
  • 16
  • 36
  • Does `txtHomePhone` represent a `TextBox`? If so, you may use the `KeyPress` event to accept the characters you would like to allow and reject what you would not like to allow to be entered in the `TextBox`. Have a great day :) – Picrofo Software Nov 06 '12 at 14:35
  • It does represent a textbox, how do I find out which keypress is which? – Wizard Nov 06 '12 at 14:37
  • Is this a web or client application? – Dan Puzey Nov 06 '12 at 14:38
  • Springfox, look at the link provided by @TyrionLannister - the first answer has some code showing you how to handle keypress events and only let digits through. If you'd prefer to keep your IF functionality above, look at davenewza's answer below (TryParse). You can also use Regex to match more complex strings and detect if a string is using a "(xxx) xxx-xxxx" format, for instance. – Joe Nov 06 '12 at 14:42

6 Answers6

11

Since txtHomePhone represents a TextBox, you may use the KeyPress event to accept the characters you would like to allow and reject what you would not like to allow in txtHomePhone

Example

public Form1()
{
    InitializeComponent();
    txtHomePhone.KeyPress += new KeyPressEventHandler(txtHomePhone_KeyPress);
}
private void txtHomePhone_KeyPress(object sender, KeyPressEventArgs e)
{
    if (e.KeyChar >= '0' && e.KeyChar <= '9' || e.KeyChar == '') //The  character represents a backspace
    {
        e.Handled = false; //Do not reject the input
    }
    else
    {
        e.Handled = true; //Reject the input
    }
}

Notice: The following character (which is not visible) represents a backspace.
Notice: You may always allow or disallow a particular character using e.Handled.
Notice: You may create a conditional statement if you would like to use -, , ( or ) only once. I would recommend you to use Regular Expressions if you would like to allow these characters to be entered in a specific position.

Example

if (e.KeyChar >= '0' && e.KeyChar <= '9' || e.KeyChar == '') //The  character represents a backspace
{
    e.Handled = false; //Do not reject the input
}
else
{
    if (e.KeyChar == ')' && !txtHomePhone.Text.Contains(")"))
    {
        e.Handled = false; //Do not reject the input
    }
    else if (e.KeyChar == '(' && !txtHomePhone.Text.Contains("("))
    {
        e.Handled = false; //Do not reject the input
    }
    else if (e.KeyChar == '-' && !textBox1.Text.Contains("-"))
    {
        e.Handled = false; //Do not reject the input
    }
    else if (e.KeyChar == ' ' && !txtHomePhone.Text.Contains(" "))
    {
        e.Handled = false; //Do not reject the input
    }
    else
    {
        e.Handled = true;
    }
}

Thanks,
I hope you find this helpful :)

Picrofo Software
  • 5,475
  • 3
  • 23
  • 37
  • allow 123( for example i tried it in visual basic .net – Eduardo Herrera Oct 23 '20 at 21:21
  • Super helpful answer, thank you. I had to use e.KeyChar=='\b' to capture the backspace (instead of e.KeyChar=='') in the Visual C# MVStudio environment. I used your pattern for accepting one instance of a specific character, to accept a decimal point in my numeric value. – veca Feb 17 '21 at 03:59
7

I'm assuming that you are using Windows Forms here, have a look at the MaskedTextBox. It allows you to specify an input mask of characters.

txtHomePhone.Mask = "##### ### ###";

Since this allows you to restrict the input values, you can safely parse the value to an integer.

Note: If you are using WPF, I don't think there is a MaskedTextBox in the base libraries, however there are extensions available on NuGet which may provide similar functionality.

Trevor Pilley
  • 16,156
  • 5
  • 44
  • 60
5

To check to see if a numeric value has been entered, you can use Integer.TryParse

int num;
bool isNum = Integer.TryParse(txtHomePhone.Text.Trim(), out num);

if (!isNum)
    //Display error
else
    //Carry on with the rest of program ie. Add Phone number to program.

BUT remember that telephone numbers aren't necessarily only numeric. Refer to Trevor Pilley answer for a masked textbox.

Dave New
  • 38,496
  • 59
  • 215
  • 394
3

Try this

if (!txtHomePhone.Text.All(c=> Char.IsNumber(c)))
{
    //Display error
}
else
{
    //Carry on with the rest of program ie. Add Phone number to program.
}
Blachshma
  • 17,097
  • 4
  • 58
  • 72
  • 1
    What does that do? It gives you a true/false value, but doesn't give any real validation. (Also, for the telephone number example used in the original question, it may not be sufficient: it'll return false for symbols and whitespace that might be in a typical phone number input.) – Dan Puzey Nov 06 '12 at 14:37
  • 1
    @DanPuzey In his example he wrote specifically: if (txtHomePhone.Text == **//something.IsNumeric** ). So i figured there are no whitspaces etc. And about validation, all he has to do is check the isNumeric. I added the code to the if statement to better explain. – Blachshma Nov 06 '12 at 14:39
0

Usually I would use Integer.TryParse as davenewza recommended, but another alternative is to use the VisualBasic IsNumeric function from C#.

Add a reference to the Microsoft.VisualBasic.dll file and then use the following code.

if (Microsoft.VisualBasic.Information.IsNumeric(txtHomePhone.Text))
{
    //Display error
}
else
{
    //Carry on with the rest of program ie. Add Phone number to program.
}
Mike Rodey
  • 296
  • 2
  • 5
0

The best way I've found to do this is to only allow the user to enter the numeric keys into the text box, thanks for your help.

Wizard
  • 1,142
  • 3
  • 16
  • 36
  • I'm glad you had your issue resolved. [Please notice that you may mark a post as an answer to indicate that you have already solved the problem](http://i.stack.imgur.com/uqJeW.png). Have a great day :) – Picrofo Software Nov 06 '12 at 14:58