If you are using VB2005 or VB2008 simply use this validation code into your textbox change event.
Method-I
Private Sub TextBox1_TextChanged(ByVal sender As Object, ByVal e As System.EventArgs) Handles TextBox1.TextChanged
If Not IsNumeric(Me.TextBox1.Text) Then
MsgBox("Please enter numeric value only", MsgBoxStyle.Information)
Me.TextBox1.Text = 0
End If
End Sub
Method-II
Private Sub TextBox1_TextChanged(ByVal sender As Object, ByVal e As System.EventArgs) Handles TextBox1.TextChanged
Dim d As Double
Dim result As Boolean result = Double.TryParse(Me.TextBox1.Text, d)
If result = False Then
MsgBox("Please enter only numeric value", MsgBoxStyle.Information) Me.TextBox1.Text = 0
End If
End Sub
For Non .net users:
Private Sub txtage_KeyPress(ByVal sender As Object, ByVal e As System.Windows.Forms.KeyPressEventArgs) Handles txtage.KeyPress
If KeyAscii(e) <> 57 Then
If KeyAscii(e) <> 8 Then e.Handled = True
End If
End If
End Sub
Public Function KeyAscii(ByVal UserKeyArgument As KeyPressEventArgs) As Short
KeyAscii = Asc(UserKeyArgument.KeyChar)
End Function
Method-III
Public Class NumericTextBox
Inherits TextBox
Private SpaceOK As Boolean = False
' Restricts the entry of characters to digits (including hex),
' the negative sign, the e decimal point, and editing keystrokes (backspace).
Protected Overrides Sub OnKeyPress(ByVal e As KeyPressEventArgs)
MyBase.OnKeyPress(e)
Dim numberFormatInfo As NumberFormatInfo = System.Globalization.CultureInfo.CurrentCulture.NumberFormat
Dim decimalSeparator As String = numberFormatInfo.NumberDecimalSeparator
Dim groupSeparator As String = numberFormatInfo.NumberGroupSeparator
Dim negativeSign As String = numberFormatInfo.NegativeSign
Dim keyInput As String = e.KeyChar.ToString()
If [Char].IsDigit(e.KeyChar) Then
' Digits are OK
ElseIf keyInput.Equals(decimalSeparator) OrElse keyInput.Equals(groupSeparator) OrElse keyInput.Equals(negativeSign) Then
' Decimal separator is OK
ElseIf e.KeyChar = vbBack Then
' Backspace key is OK
' else if ((ModifierKeys & (Keys.Control | Keys.Alt)) != 0)
' {
' // Let the edit control handle control and alt key combinations
' }
ElseIf Me.SpaceOK AndAlso e.KeyChar = " "c Then
Else
' Consume this invalid key and beep.
e.Handled = True
End If
End Sub
Public ReadOnly Property IntValue() As Integer
Get
Return Int32.Parse(Me.Text)
End Get
End Property
Public ReadOnly Property DecimalValue() As Decimal
Get
Return [Decimal].Parse(Me.Text)
End Get
End Property
Public Property AllowSpace() As Boolean
Get
Return Me.SpaceOK
End Get
Set(ByVal value As Boolean)
Me.SpaceOK = value
End Set
End Property
End Class


0 comments:
Post a Comment