Question

J'ai trouvé ce code pour faire mon textbox accepter que des chiffres.

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

Mais ... l'utilisateur ne peut pas supprimer les numéros à l'aide du bouton backspace. Comment puis-je faire?

Était-ce utile?

La solution

Vous devez également poignée texte collé (il ne peut pas être une pression de touche). La meilleure façon de le faire est avec un MaskedTextBox .

Autres conseils

 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                                

voldemort

i développer votre premier code pour permettre à l'utilisateur de supprimer aussi.

Voici le code:

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

Je espère que mon code a été utile:)

Utilisez ce code, il vous aidera à

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

Quand j'ai eu l'exigence d'une entrée qui accepte que des chiffres, j'ai généralement utilisé la classe NumericUpDown. Il gère les limites et les décimales aussi.

 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

Voici un code que je l'ai écrit. Il permet à l'utilisateur de supprimer, et l'utilisateur peut faire le vide si elles le désirent textbox. Il gère lorsque l'utilisateur tape un caractère Rejeté, et il a également des poignées lorsque l'utilisateur colle du texte dans la zone de texte. Si l'utilisateur colle une chaîne dans la boîte qui est un mélange de caractères valides et non valides, les caractères valides apparaissent dans la zone de texte, et les caractères non valides ne seront pas.

Il a également une logique en place pour faire en sorte que le curseur se comporte normalement. (Un problème avec la définition du texte à une nouvelle valeur est que le curseur est déplacé vers le début. Ce code suit la position d'origine, et fait des ajustements pour tenir compte des caractères non valides qui sont supprimés.)

Ce code peut être placé en cas TextChaned de toute zone de texte. Assurez-vous de changer le nom de TextBox1 correspondant à votre zone de texte.

    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

Remarque - si vous devez le faire pour un groupe de zones de texte, vous pouvez faire une version à usage général de ce en créant un sous qui accepte une référence à une zone de texte en tant que paramètre. Ensuite, il vous suffit d'appeler le sous de l'événement 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
Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top