VB.Net 文本框最大长度
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/25135729/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
VB.Net Textbox MaxLength
提问by ???????? ???????????
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
after i use this event with textbox maxlength is dont work
在我将此事件与文本框 maxlength 一起使用后不起作用
how to make this code with maxlength 6 character ?
如何使用 maxlength 6 个字符制作此代码?
回答by Jürgen Steinblock
Apparently MaxLength is only for User-Input. That makes sense because your text box could get data from a bound datasource and you would truncate the existing data.
显然 MaxLength 仅适用于用户输入。这是有道理的,因为您的文本框可以从绑定数据源获取数据,而您将截断现有数据。
If you do
如果你这样做
textBox1.Text = "something"
via code this is still allowed.
通过代码,这仍然是允许的。
I suggest you change your routine to
我建议你改变你的日常
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
this will not handle the input if MaxLength is reached but the control will intercept the input and provide an error sound just as every TextBox with MaxLength set.
如果达到 MaxLength,这将不会处理输入,但控件将拦截输入并提供错误声音,就像每个设置了 MaxLength 的 TextBox 一样。
回答by Shell
try like this
像这样尝试
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
回答by ???????? ???????????
You can initialize controls and variables in form loadthen the code to set the MaxLengthfor a text box in form_load as follows
您可以form load在代码中初始化控件和变量以MaxLength在 form_load 中设置文本框,如下所示
Private Sub Form2_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
txtCaptcha.MaxLength = 6
End Sub

