VB.Net Textbox MaxLength

时间:2014-08-05 09:45:42

标签: 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

使用此事件后,文本框maxlength不起作用

如何使用maxlength 6字符创建此代码?

3 个答案:

答案 0 :(得分:2)

显然MaxLength仅适用于用户输入。这是有道理的,因为您的文本框可以从绑定的数据源获取数据,并且您将截断现有数据。

如果你这样做

textBox1.Text = "something" 

通过代码,这仍然是允许的。

我建议你改变你的日常工作

    If txtCaptcha.Text.Length < txtCaptcha.MaxLength AndAlso (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

如果达到MaxLength,这将无法处理输入,但控件将拦截输入并提供错误声音,就像每个设置了MaxLength的TextBox一样。

答案 1 :(得分:1)

试试这个

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

答案 2 :(得分:0)

您可以在form load中初始化控件和变量,然后使用代码为form_load中的文本框设置MaxLength,如下所示

Private Sub Form2_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
    txtCaptcha.MaxLength = 6
End Sub