Textbox Validation for Two Decimal Places

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • Orbie
    New Member
    • Nov 2009
    • 7

    Textbox Validation for Two Decimal Places

    Hi All,
    I need to amend the code below to cater for only two Decimal places. Anyone know how i can do this?

    Code:
     Private Sub TextboxKeyPress(ByVal sender As System.Object, ByVal e As System.Windows.Forms.KeyPressEventArgs) Handles TextBox4.KeyPress, TextBox7.KeyPress
    
            Dim tb As TextBox = CType(sender, TextBox)
            Dim chr As Char = e.KeyChar
    
            If IsNumeric(e.KeyChar) And Not e.KeyChar = "-" Then
                e.Handled = Not IsNumeric(tb.Text & e.KeyChar)
            ElseIf e.KeyChar = "." Then
                If Not (tb.SelectedText = "." Or IsNumeric(tb.Text & e.KeyChar)) Then
                    e.Handled = True
                End If
            ElseIf Not Char.IsControl(e.KeyChar) Then
                e.Handled = True
            End If
        End Sub

    Thanks
  • !NoItAll
    Contributor
    • May 2006
    • 297

    #2
    Put one additional test in there...

    Code:
        Private Sub TextBox1_KeyPress(ByVal sender As Object, ByVal e As System.Windows.Forms.KeyPressEventArgs) Handles TextBox1.KeyPress
            Dim tb As TextBox = CType(sender, TextBox)
            Dim chr As Char = e.KeyChar
            Dim iLoc As Integer = 0
    
            If IsNumeric(e.KeyChar) And Not e.KeyChar = "-" Then
                e.Handled = Not IsNumeric(tb.Text & e.KeyChar)
            ElseIf e.KeyChar = "." Then
                If Not (tb.SelectedText = "." Or IsNumeric(tb.Text & e.KeyChar)) Then
                    e.Handled = True
                End If
            ElseIf Not Char.IsControl(e.KeyChar) Then
                e.Handled = True
            End If
    
            iLoc = TextBox1.Text.IndexOf(".")
            If iLoc > 0 Then
                If (TextBox1.Text.Substring(iLoc).Length > 2) And Char.IsControl(e.KeyChar) = False Then
                    e.Handled = True
                End If
            End If
    
        End Sub

    Comment

    • Frinavale
      Recognized Expert Expert
      • Oct 2006
      • 9749

      #3
      You could also consider using a MaskedTextBox. Specify that only 2 decimal places should be allowed.


      -Frinny

      Comment

      • !NoItAll
        Contributor
        • May 2006
        • 297

        #4
        Perhaps - but that control is creepy. I don't think users understand it, and getting it to behave the way you really want I've found to be more difficult than the simple routine above. The routine is small, fast and clean. You can assign it to multiple textboxes and bang, Bob's your uncle.

        Comment

        Working...