检查TextBox.Text.Length是否介于1和10之间

时间:2016-06-20 13:07:18

标签: vb.net textbox string-length

我正在尝试验证放置在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个字符的输入。我看不出我做错了什么?

3 个答案:

答案 0 :(得分:2)

首先,请勿致电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

答案 1 :(得分:0)

据我所知,这应该可以解决问题。

注意有几种不同的方法可以完成此任务,但是根据您显示的示例代码,这应该没问题。

    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

我从按钮点击事件中触发了这个。

答案 2 :(得分:0)

您必须做两件事:

  1. 将属性设置为maxlength = 10和
  2. 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
相关问题