Un textBox que acepte solo Letras en VB .NET
[Donde está Keyascci
en VB .NET]

 

Fecha: 20/Mayo/2003 (Publicado 29/Jun/03)

Autor: Angel Enrique Ruiz Pastor (Vzla), aruiz1979@hotmail.com

.

Es te código nos muestra como validar un texbox que acepte solo letras.

Abra un nuevo proyecto, En Proyectos de Visual Basic seleccione la plantilla Aplicación para Windows.

En la Barra de Herramientas Seleccione Proyecto se le desplegara una lista  seleccione Agregar Módulo.

Agregue un Textbox al Formulario y no le cambie el Nombre, Déjelo como textbox1

 
En el Modulo copie y pegue este código:
 
'****************************************************************************************
'* Código realizado por Angel Ruiz © (Venezolano)                                       *
'****************************************************************************************
 
 
  Function SoloLETRAS(ByVal KeyAscii As Integer) As Integer
        KeyAscii = Asc(UCase(Chr(KeyAscii))) 'Transformar letras minusculas a Mayúsculas
        ' Intercepta un código ASCII recibido admitiendo solamente
        ' letras, además:
        ' deja pasar sin afectar si recibe tecla de Backspace o enter
        If InStr("ABCDEFGHIJKLMNÑOPQRSTUVWXYZ", Chr(KeyAscii)) = 0 Then
            SoloLETRAS = 0
        Else
            SoloLETRAS = KeyAscii
        End If
        ' teclas adicionales permitidas
        If KeyAscii = 8 Then SoloLETRAS = KeyAscii ' Backspace
        If KeyAscii = 13 Then SoloLETRAS = KeyAscii ' Enter
    End Function
-------------------------------------------------------------------------------------------------------

Ahora valla al Formulario y haga doble click sobre el:
Después de la línea:
Inherits System.Windows.Forms.Form
 
Copie y pegue esta Declaración de Variable
Public KeyAscii As Short
 
Ahora en el evento KeyPress del textBox1 copie y pegue este código
 
 Dim KeyAscii As Short = CShort(Asc(e.KeyChar))
        KeyAscii = CShort(SoloLETRAS(KeyAscii))
        If KeyAscii = 0 Then
            e.Handled = True
        End If
 
Quedaría de la siguiente forma:
 
Private Sub TextBox1_KeyPress(ByVal sender As Object, ByVal e As System.Windows.Forms.KeyPressEventArgs) Handles TextBox1.KeyPress
        Dim KeyAscii As Short = CShort(Asc(e.KeyChar))
        KeyAscii = CShort(SoloLETRAS(KeyAscii))
        If KeyAscii = 0 Then
            e.Handled = True
        End If
 
    End Sub
 
Ahora ejecute su aplicación presionando F5.
 

ir al índice

Fichero con el código de ejemplo, (ar_SoloLetras.zip - 21,2 KB)