当达到最大限制VB.Net时,如何设置限制值文本框和显示消息框

How to set limit values textbox and show message box when reached maximum limit VB.Net

抱歉英语不好。

我是VB.NET的初学者,在这个问题上,我想进行文本框验证,以便在达到最大限制时显示消息框。下面这个代码

1
2
3
4
5
6
7
8
9
10
11
12
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


表单加载事件设置TextBox1.MaxLength = 6

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

TextBox1_KeyDown事件中使用以下代码

1
2
3
4
5
6
7
 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

保留TextBox1.MaxLength作为系统默认值,如果使用下面的代码,则无需将其长度更改为6

1
2
3
4
5
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