Search code examples
vb.netwinformsvisual-studiosubstringmaxlength

How to check if text box max length has been exceeded?


My problem:

I'm limiting a text box to 8 characters and showing a tooltip when it's exceeded (>8) rather than reached (=8). Using the .Maxlength function prevents the user from ever exceeding 8 characters so my >8 function is never fulfilled.

If I forgo the .Maxlength function and instead use .Substring to limit the input, my >8 function is fulfilled however the behavior differs from .Substring (the last rather than first 8 inputs are kept and I lose the alert sound).

It would a lot cleaner to be able to check for whenever .Maxlength is exceeded without affecting the first 8 inputs.

To reproduce:

  1. In Visual Studio, in design mode, drag a text box and tooltip onto a fresh form.
  2. Use the following as is:

Code:

Public Class Form1
    Private Sub Textbox1_TextChanged(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles TextBox1.TextChanged
        TextBox1.MaxLength = 8
        If (Not IsNumeric(TextBox1.Text) And TextBox1.Text.Length > 0) Then
            If ToolTip1.GetToolTip(TextBox1) = "" Then
                ToolTip1.ToolTipTitle = "Input must be numeric!"
                ToolTip1.Active = True
                ToolTip1.IsBalloon = True
                ToolTip1.ToolTipIcon = ToolTipIcon.Warning
                ToolTip1.Show(vbNewLine, TextBox1, 45, -40)
            End If
        ElseIf TextBox1.Text.Length > 8 Then
            'TextBox1.Text = TextBox1.Text.Substring(0, 8)
            ToolTip1.IsBalloon = True
            ToolTip1.ToolTipTitle = "8 character maximum!"
            ToolTip1.Active = True
            ToolTip1.ToolTipIcon = ToolTipIcon.Warning
            ToolTip1.Show(vbNewLine, TextBox1, 45, -40)
        Else
            ToolTip1.Active = False
            ToolTip1.Hide(TextBox1)
        End If
    End Sub
End Class

Solution

  • When you replace the text, it resets the caret, so move it back into place at the end:

    TextBox1.Text = TextBox1.Text.Substring(0, 8)
    TextBox1.Select(TextBox1.TextLength, 0)