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 :)