Jon Chance

Jon Chance

  • NA
  • 3
  • 9.6k

Delete (backspace) behavior in MaskedTextBox

Jan 25 2012 12:13 PM
Hi

I have a MaskedTextBox with the following mask 00:00:00:00 and promtChar -. '00:00:00:00' is also the default value I assign to it when the box is entered. It is to enter Timecode into.

I also validate each number as it is entered (on keyDown) to ensure it is valid for its position within the mask. If the number is invalid I suppress the keypress so nothing is entered. This is all working fine.

My issue is what happens when deleting characters. If you delete (using backspace) the second character for example on 11:10:10:24 you are left with 11:01:02:4-, ever thing has shifted down one from the point you deleted. What I want is to end up with 10:10:10:24 or 1-:10:10:24

I would like the promptChar or a 0 to be entered in place of the character deleted. I assume i can't use my promptChar due to the mask I am using only allowing numbers.

To change the behavior of the backspace I have tried to capture the backspace key, convert the maskedTextBox text to a char array and modify this by inserting a '0' into the array to replace the deleted character. By doing this I am padding the array back out (this is working correctly).

I then try to assign this array back to the maskedTextBox. This however is failing and I end up with --:--:--:-- which is my mask.

Any idea why this is not working, is there an easy way to achieve this?

Here is my code:-

if (e.KeyCode == Keys.Back)
{
 char[] textAsArray = maskedTextBox1.Text.ToCharArray();
 textAsArray[index] = Convert.ToChar("0");
 string str = textAsArray.ToString();
 maskedTextBox1.Text = str;
}


Answers (3)