0

I am working on phone number box. I have already made the format of (888)888-8888. But now I want to operate back space. If someone has given the wrong number so he can edit it.

The problem is that when I try to remove the last digits from right side. it stops removing the digits after 4 digits from end. It shows me the result like this (888)888-.

Here is my code for number and dashes format.

if (phonebox.Text.ToString().Length == 1)
                {

                    phonebox.Text = "(" + phonebox.Text.ToString();
                    phonebox.Select(phonebox.Text.Length, 0);

                }

                else if (phonebox.Text.ToString().Length == 4)
                {

                    phonebox.Text = phonebox.Text.ToString() + ")";
                    phonebox.Select(phonebox.Text.Length, 0);

                }

                else if (phonebox.Text.ToString().Length == 8)
                {

                    phonebox.Text = phonebox.Text.ToString() + "-";
                    phonebox.Select(phonebox.Text.Length, 0);

                }

here is the solution that I attempted but not sure whether it will work.

else if (phonebox.Text.ToString().Length == 9)
            {

                phonebox.Text = phonebox.Text.ToString()+"";
                phonebox.Select(phonebox.Text.Length, 0);

            }
Santosh Panda
  • 7,235
  • 8
  • 43
  • 56
Mansoor
  • 41
  • 11

2 Answers2

0

I'm not sure about your approach to deleting characters but this line is not deleting the dash, it's just appending an empty string object.

 phonebox.Text = phonebox.Text.ToString()+"";

If you want to delete the last character, you can do this

phonebox.Text = phonebox.Text.Substring(0, phonebox.Text.Length - 1)

Or, you can just replace the - with an empty string.

phonebox.Text = phonebox.Text.Replace("-", "");
keyboardP
  • 68,824
  • 13
  • 156
  • 205
0

The best way to do this is going to be adding in a extra conditional in your if and if else checks. What I want you to do is add in

(Control.ModifierKeys & Keys.Backspace) == 0 

into your conditionals

This will check and see if the pressed key was a backspace or not. If it is then it wont execute the above mods to your text field.

for example

 if ( (Control.ModifierKeys & Keys.Backspace) == 0  && phonebox.Text.ToString().Length == 1)

The SO Article referenced How to detect the currently pressed key?

Community
  • 1
  • 1
DotNetRussell
  • 9,716
  • 10
  • 56
  • 111