text box validation

L

Lal

Hi,

Any method to validate on the text box; the entering data is numeric or
text
I want to type only numeric data on the text box




Regards


K R Lal
 
Q

Qwert

Run following function in _TextChanged event.


Event:
------
Private Sub TextBox1_KeyPress(ByVal sender As System.Object, ByVal e As
System.Windows.Forms.KeyPressEventArgs) Handles TextBox1.KeyPress

TextBoxNumericOnly(Me.TextBox1, e)

End Sub


Function:
---------
Private Sub TextBoxNumericOnly(ByRef objTextBox As
System.Windows.Forms.TextBox, ByRef e As
System.Windows.Forms.KeyPressEventArgs, Optional ByVal blnAllowNegative As
Boolean = False, Optional ByVal blnAllowDecimal As Boolean = False)

Try
With objTextBox
e.Handled = True
Select Case Convert.ToInt32(e.KeyChar)
Case 48 To 57, 8, 13 ' 0 to 9, backspace, enter, delete.
e.Handled = False
Case 45 '-'.
REM You may only add 1 '-' char and only if it it
the first.
If blnAllowNegative Then
If (.Text.Length - .SelectedText.Length) = 0
Then
If .Text.LastIndexOf("-"c) = -1 Then
e.Handled = False
End If
End If
End If
Case 46 '.'.
REM You may only add 1 '.' char.
If blnAllowDecimal Then
If .Text.LastIndexOf("."c) = -1 Then
e.Handled = False
End If
End If
End Select
End With
Catch Ex As Exception
REM Handle exception.
End Try

End Sub
 
C

Cor Ligthert

Qwert,

A nice very extended function. I assume it is working. However some remarks
to make it better. First to do it completly right you have to do something
for as people are pasting in a value. That can be in an event as validating.

And than beneath in the code a little change to make it more general.
Private Sub TextBox1_KeyPress(ByVal sender As System.Object, ByVal e As
System.Windows.Forms.KeyPressEventArgs) Handles TextBox1.KeyPress

TextBoxNumericOnly(Me.TextBox1, e)
TextBoxNumericOnly(DirectCast(sender, TextBox),e)

I hope this gives some ideas

Cor
 
H

Herfried K. Wagner [MVP]

Lal said:
Any method to validate on the text box; the entering data is numeric or
text
I want to type only numeric data on the text box

Place an ErrorProvider component on the form and add this code:

\\\
Imports System.ComponentModel
..
..
..
Private Sub TextBox1_Validating( _
ByVal sender As Object, _
ByVal e As CancelEventArgs _
) Handles TextBox1.Validating
Dim SourceControl As TextBox = DirectCast(sender, TextBox)
Dim ErrorText As String
Try
Dim i As Integer = Integer.Parse(SourceControl.Text)
Catch
ErrorText = "Value must be an integer."
Finally
Me.ErrorProvider1.SetError( _
SourceControl, _
ErrorText _
)
End Try
End Sub
///
 
C

Cor Ligthert

John,

However Quert has a solution I did not see until now.
He has as complet possible done the problem.

Cor
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top