Solo acepte dígitos para el cuadro de texto
Pregunta
Encontré este código para hacer que mi cuadro de texto solo acepte números.
Private Sub TextBox1_KeyPress(ByVal sender As System.Object, ByVal e As System.Windows.Forms.KeyPressEventArgs) Handles TextBox1.KeyPress
Dim allowedChars As String = "0123456789"
If allowedChars.IndexOf(e.KeyChar) = -1 Then
' Invalid Character
e.Handled = True
End If
End Sub
Pero ... el usuario no puede eliminar los números usando el botón Backspace. ¿Cómo lo hago entonces?
Solución
También debe manejar el texto pegado (puede que no haya un KeyPress). La mejor manera de hacer esto es con un Caja de maskedText.
Otros consejos
Private Sub txtValue_KeyPress(ByVal sender As System.Object, ByVal e As System.Windows.Forms.KeyPressEventArgs) Handles txtValue.KeyPress
'Dim allowedChars As String = "0123456789"
'If allowedChars.IndexOf(e.KeyChar) = -1 Then
' ' Invalid Character
' e.Handled = True
'End If
'If (e.KeyChar = Microsoft.VisualBasic.Chr(8)) Then
' e.Handled = True
'End If
If Char.IsDigit(e.KeyChar) = False And Char.IsControl(e.KeyChar) = False Then
e.Handled = True
End If
End Sub
Desarrollo su primer código para permitir que el usuario también elimine.
Aquí está el código:
Dim BACKSPACE As Boolean
Private Sub TextBox1_KeyDown(ByVal sender As Object, ByVal e As System.Windows.Forms.KeyEventArgs) Handles TextBox1.KeyDown
If e.KeyCode = Keys.Back Then
BACKSPACE = True
Else
BACKSPACE = False
End If
End Sub
Private Sub TextBox1_KeyPress(ByVal sender As Object, ByVal e As System.Windows.Forms.KeyPressEventArgs) Handles TextBox1.KeyPress
If BACKSPACE = False Then
Dim allowedChars As String = "0123456789"
If allowedChars.IndexOf(e.KeyChar) = -1 Then
e.Handled = True
End If
End If
End Sub
Espero que mi código te haya sido útil :)
Usa este código, te ayudará
Public Function OnlyDigitsOnKeyPress(ByVal sender As Object, ByVal e As System.Windows.Forms.KeyPressEventArgs)
Try
If System.Char.IsDigit(e.KeyChar) = False And e.KeyChar <> Microsoft.VisualBasic.Chr(8) And e.KeyChar <> Microsoft.VisualBasic.Chr(46) Or (InStr(sender.text, ".") > 0 And e.KeyChar = Microsoft.VisualBasic.Chr(46))
Then
e.Handled = True
End If
Catch ex As Exception
Common.ErrorHandler(ex)
End Try
End Function
Cuando he tenido el requisito de una entrada que solo acepta números, normalmente he usado el NumericUpDown
clase. Maneja límites y decimales también.
Private Sub txtValue_KeyPress(ByVal sender As System.Object, ByVal e As System.Windows.Forms.KeyPressEventArgs) Handles txtValue.KeyPress
Dim allowedChars As String = "."
'If allowedChars.IndexOf(e.KeyChar) = -1 Then
' ' Invalid Character
' e.Handled = True
'End If
'If (e.KeyChar = Microsoft.VisualBasic.Chr(8)) Then
' e.Handled = True
'End If
If Char.IsDigit(e.KeyChar) = False And Char.IsControl(e.KeyChar) = False And allowedChars.IndexOf(e.KeyChar) = -1 Then
e.Handled = True
End If
End Sub
Aquí hay algún código que escribí. Permite al usuario eliminar, y el usuario puede dejar en blanco el cuadro de texto si lo desea. Se maneja cuando el usuario escribe un carácter no permitido, y también se maneja cuando el usuario pega el texto en el cuadro de texto. Si el usuario pasea una cadena en el cuadro que es una mezcla de caracteres válidos e inválidos, los caracteres válidos aparecerán en el cuadro de texto, y los caracteres no válidos no lo harán.
También tiene lógica para garantizar que el cursor se comporte normalmente. (Un problema con la configuración del texto en un nuevo valor es que el cursor se vuelve al principio. Este código rastrea la posición original y realiza ajustes para tener en cuenta los caracteres no válidos que se eliminan).
Este código se puede colocar en el evento TextChaned de cualquier cuadro de texto. Asegúrese de cambiar el nombre de TextBox1 para que coincida con su cuadro de texto.
Private Sub TextBox1_TextChanged(sender As System.Object, e As System.EventArgs) Handles TextBox1.TextChanged
Dim selStart As Integer = TextBox1.SelectionStart
Dim selMoveLeft As Integer = 0
Dim newStr As String = "" 'Build a new string by copying each valid character from the existing string. The new string starts as blank and valid characters are added 1 at a time.
For i As Integer = 0 To TextBox1.Text.Length - 1
If "0123456789".IndexOf(TextBox1.Text(i)) <> -1 Then 'Characters that are in the allowed set will be added to the new string.
newStr = newStr & TextBox1.Text(i)
ElseIf i < selStart Then 'Characters that are not valid are removed - if these characters are before the cursor, we need to move the cursor left to account for their removal.
selMoveLeft = selMoveLeft + 1
End If
Next
TextBox1.Text = newStr 'Place the new text into the textbox.
TextBox1.SelectionStart = selStart - selMoveLeft 'Move the cursor to the appropriate location.
End Sub
Nota: si tiene que hacer esto para un montón de cuadros de texto, puede hacer una versión de propósito general de esto creando un submarino que acepte una referencia a un cuadro de texto como parámetro. Entonces solo necesita llamar al submarino desde el evento TextChanged.
Private Sub TMarksTextBox_KeyPress(sender As Object, e As KeyPressEventArgs) Handles TMarksTextBox.KeyPress
If e.KeyChar < "0" OrElse e.KeyChar > "9" AndAlso e.KeyChar <> ControlChars.Back Then
e.Handled = True
End If
End Sub