I'm writing a WPF program where I'm trying to enter a phone number in a textbox that must be in the xxx-xxx-xxxx format. I have a key press event that parses the new input and ensures its correct, adds the new number or '-' value to the textbox and returns to wait for the next key press. My issue is this:
text box displays nothing
key press event number 5
textBox parses
call textBox.Text = "5";
exit event handling
text box displays 55 with cursor in between the 5s
Now i'm pretty sure I know that the box is updating but the actual entered text isnt being reset. How do i remove the keystroke so that the text box only displays what I set it to?
Thank you for your time.
Edit: Here's the current code if it helps.
private void PhoneNumberBox_KeyDown(object sender, KeyEventArgs e)
{
String keyString = e.Key.ToString();
char keyPress = 'x';
if (keyString.Length == 2 && keyString[0] == 'D')
keyPress = keyString[1];
TextBox textBox = sender as TextBox;
if ((keyPress > 47 && keyPress < 58) || keyPress == '-')
{
int length = _textBoxText.Length;
switch (length)
{
case 0:
case 1:
case 2:
case 4:
case 5:
case 6:
case 8:
case 9:
case 10:
case 11:
{
if (keyPress != '-')
_textBoxText += keyPress;
break;
}
case 3:
case 7:
{
if (keyPress == '-')
_textBoxText += keyPress;
break;
}
}
textBox.Clear();
textBox.Text = _textBoxText;
}
else
Invalid_Entry(textBox);
}