HunderingThooves
HunderingThooves

Reputation: 992

Limiting the number of characters you can enter into a Windows Forms textbox

Assuming that I have a Windows Forms textbox and want to reduce the maximum amount of characters that can be allowed in via user entry, how would I do that?

Upvotes: 3

Views: 26549

Answers (3)

Tiny Gipxy
Tiny Gipxy

Reputation: 121

Set MaxLength does not work with isNumber=true, you still can input 00012 regardless of limit = 4

My solution:

Protected Overridable Sub szSeqNmbr_KeyPress(ByVal eventSender As System.Object, ByVal    eventArgs As System.Windows.Forms.KeyPressEventArgs) Handles szAuthID.KeyPress
    Dim KeyAscii As Short = Convert.ToInt32(eventArgs.KeyChar)

    If (szAuthID.Text.Length >= szAuthID.MaxLength) Then
        'szAuthID.Text = szAuthID.Text.Substring(0, szAuthID.MaxLength)
        If (KeyAscii >= 48 And KeyAscii <= 57) Then
            eventArgs.Handled = True
            Return
        End If
    End If
End Sub

Upvotes: 1

Darin Dimitrov
Darin Dimitrov

Reputation: 1038720

You could use the MaxLength property to set the maximum number of characters allowed in a textbox.

Upvotes: 2

Hans Passant
Hans Passant

Reputation: 941317

Set the MaxLength property. No code required, you can set it in the designer.

Upvotes: 8

Related Questions