Validações úteis para TextBox

Veja nesta dica de Rafael Nascimento algumas validações interessantes para o componente TextBox.

Listagem 1. TextBox numérica
 
    Private Sub TextBox1_KeyPress(ByVal sender As Object, _

    ByVal e As System.Windows.Forms.KeyPressEventArgs) _

    Handles TextBox1.KeyPress


        If (Not (Char.IsDigit(e.KeyChar) _

        Or Char.IsControl(e.KeyChar))) Then

            e.Handled = True

        End If


    End Sub
            
Listagem 2. TextBox numérica com decimais
 
    Private Sub TextBox1_KeyPress(ByVal sender As Object, _

    ByVal e As System.Windows.Forms.KeyPressEventArgs) _

    Handles TextBox1.KeyPress


        If (Not (Char.IsDigit(e.KeyChar) _

        Or Char.IsControl(e.KeyChar) _

        Or (e.KeyChar = Chr(46)))) Then

            e.Handled = True

        End If


    End Sub
            
Listagem 3. TextBox permitindo somente caracteres alfabéticos
 
    Private Sub TextBox1_KeyPress(ByVal sender As Object, _

    ByVal e As System.Windows.Forms.KeyPressEventArgs) _

    Handles TextBox1.KeyPress
 

        If (Not (Char.IsLetter(e.KeyChar) Or _

        Char.IsControl(e.KeyChar))) Then

            e.Handled = True

        End If


    End Sub
            
Listagem 4. TextBox permitindo somente caracteres maiúsculos
 
    Private Sub TextBox1_KeyPress(ByVal sender As Object, _

    ByVal e As System.Windows.Forms.KeyPressEventArgs) _

    Handles TextBox1.KeyPress


        If (Not (Char.IsUpper(e.KeyChar) _

        Or Char.IsControl(e.KeyChar))) Then

            e.Handled = True

        End If


    End Sub
            
Listagem 5. TextBox permitindo somente caracteres minúsculos
 
    Private Sub TextBox1_KeyPress(ByVal sender As Object, _

    ByVal e As System.Windows.Forms.KeyPressEventArgs) _

    Handles TextBox1.KeyPress


        If (Not (Char.IsLower(e.KeyChar) _

        Or Char.IsControl(e.KeyChar))) Then

            e.Handled = True

        End If


    End Sub
            
Listagem 6. Verificar se um TextBox está preenchido
 
    ' Chame esta função e passe a TextBox 

    ' como parâmetro

    Public Shared Function VerificarVazio _

    (ByVal ParamArray tb As System.Windows.Forms.TextBox()) _

    As Boolean

 
        Dim i As Integer
 

        For i = 0 To tb.Length

            If tb(i).Text.Trim().Equals("") Then

                MessageBox.Show("Não deixe este campo vazio")

                tb(i).Focus()

                Return False

            End If

        Next


        Return True


    End Function
            

Artigos relacionados