[英]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個字符?
顯然,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一樣。
這樣嘗試
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
您可以在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
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.