0

Sorry for bad english.

I'm beginner in VB.Net, on this question I want to make textbox validation to show messagebox when maximum limit is reached. below this code

Public Class Form1

    Private Sub TextBox1_TextChanged(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles TextBox1.TextChanged
        Dim i As Integer
        TextBox1.MaxLength = 6
        i = TextBox1.MaxLength

        If TextBox1.Text.Length > i Then
            MsgBox("Maximum is 6 Character")
        End If
    End Sub
End Class
1
  • If you set the MaxLength property you cannot use this event because your text will never be more that 6 characters. It is the control itself that doesn't accept any input after the 6th character
    – Steve
    Commented Dec 14, 2015 at 10:18

1 Answer 1

1

In form load event set TextBox1.MaxLength = 6

Private Sub Form1_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
      TextBox1.MaxLength = 6
 End Sub

and use the following code in TextBox1_KeyDown event

 Private Sub TextBox1_KeyDown(ByVal sender As Object _
                             , ByVal e As System.Windows.Forms.KeyEventArgs _
                             ) Handles TextBox1.KeyDown
    If Trim(TextBox1.Text).Length = 6 Then
        MsgBox("Maximum is 6 Character")
    End If
End Sub

Or

Keep TextBox1.MaxLength as system default,if you use below code then no need to alter it's lenghth to 6

Private Sub TextBox1_KeyPress(ByVal sender As Object, ByVal e As System.Windows.Forms.KeyPressEventArgs) Handles TextBox1.KeyPress
        If Trim(TextBox1.Text).Length = 6 Then
            e.Handled = True
            MsgBox("Maximum is 6 Character")
        End If
End Sub
2
  • Why the Load event? I thought that was anti-pattern. Why not the constructor or the OnLoad event?
    – Sam Makin
    Commented Dec 14, 2015 at 10:21
  • It's work well, thank you very much for your answer. Commented Dec 14, 2015 at 12:54

Not the answer you're looking for? Browse other questions tagged or ask your own question.