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

时间:2015-12-14 10:07:29

标签: vb.net

抱歉英文不好。

我是VB.Net的初学者,在这个问题上,我想让文本框验证在达到最大限制时显示消息框。 低于此代码

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 个答案:

答案 0 :(得分:1)

在表单加载事件集TextBox1.MaxLength = 6

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

并在TextBox1_KeyDown 事件

中使用以下代码
 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

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