Here are a couple ideas
- Use a custom TextBox (note IsNumeric assertions)
- For a regular TextBox use either TextChanged or KeyPress events
The following are basics that can be expanded on
Public Class Form1
Private Sub IsNumberButton_Click(sender As Object, e As EventArgs) Handles IsNumberButton.Click
If SpecialTextBox1.IsNumeric Then
MessageBox.Show("Numeric")
Else
MessageBox.Show("Not numeric")
End If
End Sub
''' <summary>
''' Integer, Decimal, Double
''' </summary>
''' <param name="sender"></param>
''' <param name="e"></param>
Private Sub TextBox1_KeyPress(sender As Object, e As KeyPressEventArgs) Handles TextBox1.KeyPress
If Not Char.IsControl(e.KeyChar) AndAlso Not Char.IsDigit(e.KeyChar) AndAlso (e.KeyChar <> "."c) Then
e.Handled = True
End If
If (e.KeyChar = "."c) AndAlso ((TryCast(sender, TextBox)).Text.IndexOf("."c) > -1) Then
e.Handled = True
End If
End Sub
''' <summary>
''' Integer only
''' </summary>
''' <param name="sender"></param>
''' <param name="e"></param>
Private Sub TextBox2_TextChanged(sender As Object, e As EventArgs) Handles TextBox2.TextChanged
Dim textBox = ctype(sender, TextBox)
If System.Text.RegularExpressions.Regex.IsMatch(TextBox.Text, "[^0-9]") Then
TextBox.Text = TextBox2.Text.Remove(TextBox.Text.Length - 1)
End If
End Sub
End Class
Public Class SpecialTextBox
Inherits TextBox
''' <summary>
''' Determine if we are dealing with a number
''' </summary>
''' <returns></returns>
Public ReadOnly Property IsNumeric() As Boolean
Get
If Double.TryParse(Text.Replace(" "c, "").Trim(), Nothing) Then
Return True
Else
Return False
End If
End Get
End Property
End Class