I'm attempting to write a function that checks users input and verifies it's numeric. When it isn't I would like to keep the part of the string that's numeric and remove the last character after a messagebox pops up alerting the user to the violation. Here is the code I have thus far:

If TypeName(Me.ActiveControl) = "TextBox" Then
With Me.ActiveControl
If Not IsNumeric(.Text) And .Text <> vbNullString Then
MessageBox.Show("Sorry, only numbers allowed")
.Text = .Text vbNullString
End If
End With
End If

But this erases the entire textbox string and I have to start over.

Any help would be greatly appreciated.

Recommended Answers

All 3 Replies

hmm... see this code. its wont to allowed you input other character except number.

Private Sub TextBox1_KeyPress(ByVal sender As Object, ByVal e As System.Windows.Forms.KeyPressEventArgs) Handles TextBox1.KeyPress
If (Microsoft.VisualBasic.Asc(e.KeyChar) < 48) _
               Or (Microsoft.VisualBasic.Asc(e.KeyChar) > 57) Then
            e.Handled = True
        End If
        If (Microsoft.VisualBasic.Asc(e.KeyChar) = 8) Then
            e.Handled = False
        End If
end sub
x = TextBox1.Text.ToCharArray
While continue = True And (i < x.Length)
            If IsNumeric(x(i)) Then
                y += x(i)
            Else
                continue = False
                MessageBox.Show("Sorry, only numbers allowed")
            End If
            i = i + 1
        End While

        TextBox1.Text = y

any way I think not allowing user from start to violate the rules as Jx_Man suggested is better

any way I think not allowing user from start to violate the rules as Jx_Man suggested is better

As Alan Cooper said, and I paraphrase, "The best way to handle errors is to never let them be made."

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.