vb.net 检查 TextBox.Text.Length 是否在 1 到 10 之间

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/37923422/
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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-17 19:57:48  来源:igfitidea点击:

Checking that TextBox.Text.Length is between 1 and 10

vb.nettextboxstring-length

提问by TM80

I am trying to validate the number of characters placed inside a TextBoxbut am having some trouble. The code I'm using is as follows:

我正在尝试验证放置在 a 中的字符数,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

What I want is for TextBox5to have a length between (and inclusive) 1 and 10, if not reselect the TextBoxmaking it ready for another user input.

我想要的是TextBox5在(包括)1 和 10 之间的长度,如果没有重新选择TextBox使其为另一个用户输入做好准备。

The code responds well for an input less than 1 but fails to recognise any input larger than 10 characters. I can't see what i'm doing wrong?

该代码对小于 1 的输入响应良好,但无法识别大于 10 个字符的任何输入。我看不出我做错了什么?

回答by jmcilhinney

Firstly, don't call Focus. The documentation clearly states, don't call Focus. If you want to focus a control, you call its Selectmethod.

首先,不要打电话Focus。文档明确指出,不要调用Focus. 如果你想聚焦一个控件,你可以调用它的Select方法。

You don't need to call either though. You should be handling the Validatingevent and if the control fails validation, you set e.Cancelto Trueand the control will not lose focus in the first place.

你也不需要打电话。您应该处理该Validating事件,如果控件未通过验证,则设置e.CancelTrue并且控件首先不会失去焦点。

If myTextBox.TextLength < 1 OrElse myTextBox.TextLength > 10 Then
    'Validation failed.
    myTextBox.SelectAll()
    e.Cancel = True
End If

回答by user1234433222

From what I can understand, this should do the trick.

NOTEThere are a few different ways to achieve this task, however from there sample code you have shown, this should be fine.

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

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

    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

I have this triggering from a button click event.

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