Question validation problem

swethajain

Well-known member
Joined
Feb 1, 2010
Messages
48
Programming Experience
Beginner
Hi,
I have a problem regarding validation. ehen the % textbox is empty it is not getting validated. the code is,


Private Sub txtbx_Percent_Validating(ByVal sender As Object, ByVal e As System.ComponentModel.CancelEventArgs) Handles TextBoxPercent.Validating
Validate_Percentage()
End Sub

Private Function Validate_Percentage() As Boolean
'Dim bStatus As Boolean = True
If TextBoxPercent.Text <= 0 Or TextBoxPercent.Text > 100 Or TextBoxPercent.Text = "" Then
MsgBox("Precentage should be between 0 to 100")
TextBoxPercent.Clear()
TextBoxPercent.Focus()
TextBoxPercent.BackColor = Color.Red
'bStatus = False
Else
TextBoxPercent.Text = Val(TextBoxPercent.Text)
TextBoxPercent.BackColor = Color.White
'Return (bStatus)
End If

End Function


Private Sub txtbx_Percent_KeyPress(ByVal sender As Object, ByVal e As System.Windows.Forms.KeyPressEventArgs) Handles TextBoxPercent.KeyPress
Dim allowedChars As String = "0123456789"
Dim disallowedChars As String = "abcdefghijklmnopqrstuvwxyz!@#$%&()-[]{}"
If allowedChars.IndexOf(e.KeyChar) = -1 Then
' Invalid(Character)
MsgBox("Enter numeric data")
TextBoxPercent.Focus()
End If
If allowedChars.IndexOf(e.KeyChar) = -1 Then
' Invalid Character

TextBoxPercent.Focus()
e.Handled = True
End If

End Sub
 
VB.NET:
    Private Sub TextBoxPercent_KeyPress(ByVal sender As Object, ByVal e As System.Windows.Forms.KeyPressEventArgs) Handles TextBoxPercent.KeyPress
        e.Handled = True 'cancel the keypress
        If IsNumeric(e.KeyChar) Then
            e.Handled = False 'resume keypress 
        End If
    End Sub


    Private Sub TextBoxPercent_TextChanged(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles TextBoxPercent.TextChanged
        If Integer.Parse(TextBoxPercent.Text) <= 0 Or _
            Integer.Parse(TextBoxPercent.Text) > 100 Or _
            TextBoxPercent.Text = String.Empty Then
            MessageBox.Show("Precentage should be between 0 to 100")
            TextBoxPercent.Text = "0"
            TextBoxPercent.Select(0, TextBoxPercent.Text.Length)
        End If
    End Sub

You need only these two event handlers ;)
 
Back
Top