Para colocar uma máscara de data no TextBox para que a barra(\) apareça
automaticamente coloque os códigos abaixo no evento TextBox1_KeyPress:
'Cancelar as teclas de
letras, acentos e outros caracteres não numéricos
If No tChar.IsNumber(e.KeyChar)
And
e.KeyChar <> Chr(8) And
e.KeyChar <> Chr(13) Then
e.Handled = True
End If
'Máscara de data com a barra
If
IsNumeric(e.KeyChar) = True Then
Select Case
TextBox1.TextLength
Case 0
TextBox1.Text = ""
Case 2
TextBox1.Text = TextBox1.Text + "/"
TextBox1.SelectionStart = 4
Case 5
TextBox1.Text = TextBox1.Text + "/"
TextBox1.SelectionStart = 7
End Select
End If
'Limita o textbox a 10 caracteres
If
TextBox1.TextLength = 10 Then
If Not e.KeyChar = Chr(8)
Then
e.Handled = True
TextBox1.SelectionStart = TextBox1.TextLength
End If
End If
'Retirar a / das posições e o número anterior
If
TextBox1.TextLength <> 0 Then
If
e.KeyChar = Chr(8) And
TextBox1.TextLength = TextBox1.Text.LastIndexOf("/")
+ 1 Then
TextBox1.Text = TextBox1.Text.Substring(0, TextBox1.TextLength - 1)
TextBox1.SelectionStart = TextBox1.TextLength
End If
End If
'Testa a data quando a tecla enter é precionada
If
e.KeyChar = Chr(13) Then
If IsDate(TextBox1.Text)
= False Or TextBox1.TextLength
= 9 Then
MsgBox("Data Inválida!",
16, "Erro")
Exit Sub
Else
TextBox1.Text = Format(CDate(TextBox1.Text),
"dd/MM/yy")
End If
End If
Você pode colocar a última parte, quando se verifica se a data é válida no
evento TextBox1_Leave, basta retirar o “If
e.KeyChar = Chr(13) Then”.
Simples, não?
Acho que assim fica melhor.
ResponderExcluirPrivate Sub TextBox1_KeyPress(sender As Object, e As System.Windows.Forms.KeyPressEventArgs) Handles TextBox1.KeyPress
If Not Char.IsNumber(e.KeyChar) And e.KeyChar <> Chr(8) And e.KeyChar <> Chr(13) Then
e.Handled = True
End If
'Máscara de data com a barra
If IsNumeric(e.KeyChar) = True Then
Select Case TextBox1.TextLength
Case 0
TextBox1.Text = ""
Case 2
TextBox1.Text = TextBox1.Text + "/"
TextBox1.SelectionStart = 4
Case 5
TextBox1.Text = TextBox1.Text + "/"
TextBox1.SelectionStart = 6
End Select
End If
'Limita o textbox a 10 caracteres
If TextBox1.TextLength = 10 Then
If Not e.KeyChar = Chr(8) Then
e.Handled = True
TextBox1.SelectionStart = TextBox1.TextLength
End If
End If
'Retirar a / das posições e o número anterior
If TextBox1.TextLength <> 0 Then
If e.KeyChar = Chr(8) And TextBox1.TextLength = TextBox1.Text.LastIndexOf("/") - 1 Then
TextBox1.Text = TextBox1.Text.Substring(0, TextBox1.TextLength - 1)
TextBox1.SelectionStart = TextBox1.TextLength
End If
End If
'Testa a data quando a tecla enter é precionada
If e.KeyChar = Chr(13) Then
If IsDate(TextBox1.Text) = False Or TextBox1.TextLength = 9 Then
MsgBox("Data Inválida!", 16, "Erro")
Exit Sub
Else
TextBox1.Text = Format(CDate(TextBox1.Text), "dd/MM/yy")
End If
End If
End Sub
muito obrigado ao anonimo ai! finalmente encontrei
ResponderExcluir