检查 TextBox.Text.Length 是否在 1 到 10 之间
Checking that TextBox.Text.Length is between 1 and 10
我正在尝试验证 TextBox
中放置的字符数,但遇到了一些问题。我使用的代码如下:
If Not ((TextBox5.Text.Length) <= 1) Or ((TextBox5.Text.Length) >= 10) Then
MsgBox("Invalid date entry. Use the the following format: DD-MM-YYYY.")
TextBox5.Focus()
TextBox5.SelectAll()
Else
'do whatever
End If
我想要的是 TextBox5
的长度介于(含)1 和 10 之间,如果不重新选择 TextBox
使其为另一个用户输入做好准备。
对于小于 1 个字符的输入,代码响应良好,但无法识别大于 10 个字符的输入。我看不出我做错了什么?
首先,不要打电话给Focus
。文档中明确指出,不要调用 Focus
。如果你想聚焦一个控件,你调用它的 Select
方法。
不过你也不需要打电话。您应该处理 Validating
事件,如果控件验证失败,您将 e.Cancel
设置为 True
并且控件不会首先失去焦点。
If myTextBox.TextLength < 1 OrElse myTextBox.TextLength > 10 Then
'Validation failed.
myTextBox.SelectAll()
e.Cancel = True
End If
据我所知,这应该可以解决问题。
注意有几种不同的方法可以完成此任务,但是从您展示的示例代码来看,这应该没问题。
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
If TextBox5.Text.Length < 1 Or TextBox5.Text.Length > 10 Then
MsgBox("Invalid date entry. Use the the following format: DD-MM-YYYY.")
TextBox1.SelectAll()
Else
MessageBox.Show("date accepted...")
End If
End Sub
我通过按钮点击事件触发了这个。
您必须做两件事:
- 属性设置为 maxlength=10 和
- 处理 KeyPressEventArgs
像这样:
Private Sub res_pin_KeyPress(sender As Object, e As KeyPressEventArgs) Handles res_pin.KeyPress
If e.KeyChar = Chr(13) Then
If Me.res_pin.Text.Length < 6 Then
e.Handled = True
Else
Me.res_deposit.Focus()
End If
End If
End Sub
我正在尝试验证 TextBox
中放置的字符数,但遇到了一些问题。我使用的代码如下:
If Not ((TextBox5.Text.Length) <= 1) Or ((TextBox5.Text.Length) >= 10) Then
MsgBox("Invalid date entry. Use the the following format: DD-MM-YYYY.")
TextBox5.Focus()
TextBox5.SelectAll()
Else
'do whatever
End If
我想要的是 TextBox5
的长度介于(含)1 和 10 之间,如果不重新选择 TextBox
使其为另一个用户输入做好准备。
对于小于 1 个字符的输入,代码响应良好,但无法识别大于 10 个字符的输入。我看不出我做错了什么?
首先,不要打电话给Focus
。文档中明确指出,不要调用 Focus
。如果你想聚焦一个控件,你调用它的 Select
方法。
不过你也不需要打电话。您应该处理 Validating
事件,如果控件验证失败,您将 e.Cancel
设置为 True
并且控件不会首先失去焦点。
If myTextBox.TextLength < 1 OrElse myTextBox.TextLength > 10 Then
'Validation failed.
myTextBox.SelectAll()
e.Cancel = True
End If
据我所知,这应该可以解决问题。
注意有几种不同的方法可以完成此任务,但是从您展示的示例代码来看,这应该没问题。
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
If TextBox5.Text.Length < 1 Or TextBox5.Text.Length > 10 Then
MsgBox("Invalid date entry. Use the the following format: DD-MM-YYYY.")
TextBox1.SelectAll()
Else
MessageBox.Show("date accepted...")
End If
End Sub
我通过按钮点击事件触发了这个。
您必须做两件事:
- 属性设置为 maxlength=10 和
- 处理 KeyPressEventArgs
像这样:
Private Sub res_pin_KeyPress(sender As Object, e As KeyPressEventArgs) Handles res_pin.KeyPress
If e.KeyChar = Chr(13) Then
If Me.res_pin.Text.Length < 6 Then
e.Handled = True
Else
Me.res_deposit.Focus()
End If
End If
End Sub