Search code examples
vb.nettextboxmaxlength

VB.Net Textbox MaxLength


Private Sub txtCaptcha_KeyPress(sender As Object, e As KeyPressEventArgs) Handles txtCaptcha.KeyPress
    If Char.IsLower(e.KeyChar) Or Char.IsNumber(e.KeyChar) Then
        Dim pos As Integer = txtCaptcha.SelectionStart
        txtCaptcha.Text = txtCaptcha.Text & Char.ToUpper(e.KeyChar)
        txtCaptcha.SelectionStart = pos + 1
        e.Handled = True
    End If
End Sub

after i use this event with textbox maxlength is dont work

how to make this code with maxlength 6 character ?


Solution

  • try like this

    Private Sub txtCaptcha_KeyPress(sender As Object, e As KeyPressEventArgs) Handles txtCaptcha.KeyPress
        If txtCaptcha.MaLength = txtCaptcha.Text.Length Then
            e.Handled = true
            Exit Sub
        End If
    
        'For Ctrl+V
        If AscW(e.KeyChar) = 22 Then
            Dim strPaste As String = My.Computer.Clipboard.GetText() & txtCaptcha.Text
            If strPaste.Length > txtCaptcha.MaLength Then
                strPaste = strPaste.Substring(0, txtCaptcha.MaLength)
                txtCaptcha.Text = strPaste
                e.Handled = True
                Exit Sub
            End If
        End If
    
        If Char.IsLower(e.KeyChar) Or Char.IsNumber(e.KeyChar) Then
            Dim pos As Integer = txtCaptcha.SelectionStart
            txtCaptcha.Text = txtCaptcha.Text & Char.ToUpper(e.KeyChar)
            txtCaptcha.SelectionStart = pos + 1
            e.Handled = True
        End If
    End Sub