Since txtHomePhone represents a TextBox , you can use the KeyPress event to accept the characters you want to allow and reject what you would not want 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 == '')
Note : The following character (which is not displayed) represents the inverse space.
Note You can always enable or disable a specific character using e.Handled .
Note You can create a conditional statement if you want to use - , , ( or ) only once. I would recommend that you use regular expressions if you want these characters to be entered at 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,
Hope you find this helpful :)
source share