Validating a textbox to allow only numeric values
c#, validation
Solution
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 :)
Problem
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?