We help IT Professionals succeed at work.
Get Started

Keypress code that treats textbox as empty when all text is highlighted

Last Modified: 2013-11-17
Using Vb.net 2005 compact framework

I have some keypress code to check to see if the value has more than two places of decimal. It all works fine except for one annoying thing. If the value in the textbox is at two places of decimal, but the user wants to change the value, they have to hi-lite the value and hit the backspace key and then enter the new value.

I want to avoid the user having to use the backspace step. I want them to just start typing the value and it replace the old value. It does do it so long as the user is at 0 or 1 places of decimal. If they go to 2 places it won't work.

Please help me fix this.



        If Not Char.IsDigit(e.KeyChar) And Not e.KeyChar = "." And Not e.KeyChar = ChrW(8) Then
            e.Handled = True
            If e.KeyChar = "." And txt1.Text.IndexOf(".") <> -1 Then
                e.Handled = True
            ElseIf e.KeyChar = "." Then
                e.Handled = False
            ElseIf Char.IsDigit(e.KeyChar) Then
                If txt1.Text.IndexOf(".") <> -1 Then
                    If txt1.Text.Length >= txt1.Text.IndexOf(".") + 3 Then
                        e.Handled = True
                    End If
                End If
            End If
        End If

Open in new window

Watch Question
Top Expert 2007
This problem has been solved!
Unlock 1 Answer and 6 Comments.
See Answer
Why Experts Exchange?

Experts Exchange always has the answer, or at the least points me in the correct direction! It is like having another employee that is extremely experienced.

Jim Murphy
Programmer at Smart IT Solutions

When asked, what has been your best career decision?

Deciding to stick with EE.

Mohamed Asif
Technical Department Head

Being involved with EE helped me to grow personally and professionally.

Carl Webster
CTP, Sr Infrastructure Consultant
Ask ANY Question

Connect with Certified Experts to gain insight and support on specific technology challenges including:

  • Troubleshooting
  • Research
  • Professional Opinions
Did You Know?

We've partnered with two important charities to provide clean water and computer science education to those who need it most. READ MORE