VB.NET和Windows窗体中的TextBox验证

时间:2022-01-06 15:51:06

I'm using the following code to validate the text entered by user. It works perfectly fine. But I want to add the backspace feature so as to allow the user to delete the wrongly entered number.

我正在使用以下代码来验证用户输入的文本。它工作得非常好。但我想添加退格功能,以便允许用户删除错误输入的号码。

I have tried a couple of things and they worked but before last digit (after the decimal point) i.e. it does not allows to delete after the number has been completely entered. number is being entered in the format: 12313213.45

我已经尝试了一些东西,但它们在最后一个数字之前(小数点后)工作,即在完全输入数字后它不允许删除。号码输入格式为:12313213.45

What shall I do?

我该怎么办?

Private Sub TextBox5_KeyPress(ByVal sender As Object, ByVal e As System.Windows.Forms.KeyPressEventArgs) Handles TextBox5.KeyPress

    'validation '
    Dim KeyAscii As Short = Asc(e.KeyChar)
    If Not ((KeyAscii >= System.Windows.Forms.Keys.D0 And KeyAscii <= System.Windows.Forms.Keys.D9) Or (KeyAscii = System.Windows.Forms.Keys.Back) Or Chr(KeyAscii) = "." Or (Chr(KeyAscii) Like "[ ]")) Then
        KeyAscii = 0
        TextBox5.Focus()
    End If
    If KeyAscii = 0 Then
        e.Handled = True
    End If

    If TextBox5.Text.IndexOf(".") >= 0 And e.KeyChar = "." Then
        e.Handled = True
    End If

    If TextBox5.Text.IndexOf(".") > 0 Then
        If TextBox5.SelectionStart > TextBox5.Text.IndexOf(".") Then
            If TextBox5.Text.Length - TextBox5.Text.IndexOf(".") = 3 Then
                e.Handled = True
            End If
        End If
    End If
End Sub

7 个解决方案

#1


There is a much easier way to validate this. Try convert the text in the edit box to a floating point number. If you catch an exception, the number is not valid.

有一种更简单的方法来验证这一点。尝试将编辑框中的文本转换为浮点数。如果您发现异常,则该号码无效。

Trying to validate keystroke by keystroke is going to cause you many headaches.

尝试通过击键来验证击键会让你感到很头疼。

#2


An even better way is to use a control that supports decimals (if that is you're using something like infragistics, componentone, devexpress, etc.) The user gets visual cues and can do neat things like click the arrows to advance the numbers.

更好的方法是使用支持小数的控件(如果你正在使用像infragistics,componentone,devexpress等那样的东西)用户获得视觉提示并且可以做一些整洁的事情,比如点击箭头来推进数字。

If you're using plain old winforms, have a look at the masked edit control.

如果您使用普通的旧winforms,请查看屏蔽的编辑控件。

Personally I find it HUGELY irritating when applications try to correct me and i'm not done entering data. It's much more user friendly to let the user finish and then notify them if there are any problems.

就个人而言,当应用程序试图纠正我并且我没有输入数据时,我发现它很恼火。让用户完成然后在有任何问题时通知他们更方便用户。

#3


txtMobil.Text = Format(txtMobil.Text, "###-###-####")

#4


Don't try and validate keystrokes one at a time.
1) You have just found that backspace requires more code, now add support for cut/copy and paste, and the delete key and typing replaces selection. The code is not nice.
2) It will only confuse the user. Or worse, they try and type a . seperated date into your field, you force that date into a legitimate number by ignoring the second . and they have now entered something totally wrong and your program won't tell them.
The validating event of the textbox is where this sort of logic should go. It will fire when the focus moves to another control (whose CausesValidation property is true, this allows cancel buttons to be clicked even if the current control is not in a valid state).
In the validating event you can do all the checks you need to and cancel the event if the data is not valid, as well as displaying whatever message you need to. To validate the value I would suggest Single.TryParse to start with, then if the conversion succeeds you can continue to do any range checks that you require. TryParse is better than @Bork's suggestion because it is easier to read and avoids the throwing/catching of un-necessary exceptions.

不要一次尝试和验证一次击键。 1)您刚刚发现退格需要更多代码,现在添加对剪切/复制和粘贴的支持,删除键和键入替换选择。代码不太好。 2)它只会使用户感到困惑。或者更糟糕的是,他们尝试输入一个。在您的字段中分隔日期,您可以通过忽略第二个日期将该日期强制为合法数字。他们现在输入了一些完全错误的东西,你的程序也不会告诉他们。文本框的验证事件是这种逻辑应该去的地方。当焦点移动到另一个控件(其CausesValidation属性为true时,它将触发,即使当前控件未处于有效状态,也允许单击取消按钮)。在验证事件中,您可以执行所需的所有检查,并在数据无效时取消事件,并显示您需要的任何消息。要验证值,我建议使用Single.TryParse,然后如果转换成功,您可以继续进行所需的任何范围检查。 TryParse比@ Bork的建议更好,因为它更容易阅读并避免抛出/捕获不必要的异常。

EDIT: Just noticed you are also restricting the length of the entered text. You can do that by setting the MaxLength property of the TextBox.

编辑:刚刚注意到你也在限制输入文本的长度。您可以通过设置TextBox的MaxLength属性来实现。

#5


I think the link below should give you exactly what you're after:

我认为下面的链接应该能够准确地告诉您:

Numeric TextBox

Although it requires a fair amount of code to handle validation on each keypress, it's certainly possible, and the code above seems to handle delete, backspace, copy/pasting etc.

虽然它需要相当数量的代码来处理每个按键的验证,但它当然是可能的,并且上面的代码似乎处理删除,退格,复制/粘贴等。

#6


Or use a regular expression for the tough stuff

或者使用正则表达式来处理棘手的事情

#7


Yeah, or just make that nested if...then block look like this:

是的,或者只是嵌套if ... then块看起来像这样:

If Textbox5.Text.IndexOf(".") > 0 Then
    If Textbox5.SelectionStart > Textbox5.Text.IndexOf(".") Then
        If Textbox5.Text.Length - Textbox5.Text.IndexOf(".") = 3 Then
            If KeyAscii <> System.Windows.Forms.Keys.Back Then e.Handled = True
        End If
    End If
End If

#1


There is a much easier way to validate this. Try convert the text in the edit box to a floating point number. If you catch an exception, the number is not valid.

有一种更简单的方法来验证这一点。尝试将编辑框中的文本转换为浮点数。如果您发现异常,则该号码无效。

Trying to validate keystroke by keystroke is going to cause you many headaches.

尝试通过击键来验证击键会让你感到很头疼。

#2


An even better way is to use a control that supports decimals (if that is you're using something like infragistics, componentone, devexpress, etc.) The user gets visual cues and can do neat things like click the arrows to advance the numbers.

更好的方法是使用支持小数的控件(如果你正在使用像infragistics,componentone,devexpress等那样的东西)用户获得视觉提示并且可以做一些整洁的事情,比如点击箭头来推进数字。

If you're using plain old winforms, have a look at the masked edit control.

如果您使用普通的旧winforms,请查看屏蔽的编辑控件。

Personally I find it HUGELY irritating when applications try to correct me and i'm not done entering data. It's much more user friendly to let the user finish and then notify them if there are any problems.

就个人而言,当应用程序试图纠正我并且我没有输入数据时,我发现它很恼火。让用户完成然后在有任何问题时通知他们更方便用户。

#3


txtMobil.Text = Format(txtMobil.Text, "###-###-####")

#4


Don't try and validate keystrokes one at a time.
1) You have just found that backspace requires more code, now add support for cut/copy and paste, and the delete key and typing replaces selection. The code is not nice.
2) It will only confuse the user. Or worse, they try and type a . seperated date into your field, you force that date into a legitimate number by ignoring the second . and they have now entered something totally wrong and your program won't tell them.
The validating event of the textbox is where this sort of logic should go. It will fire when the focus moves to another control (whose CausesValidation property is true, this allows cancel buttons to be clicked even if the current control is not in a valid state).
In the validating event you can do all the checks you need to and cancel the event if the data is not valid, as well as displaying whatever message you need to. To validate the value I would suggest Single.TryParse to start with, then if the conversion succeeds you can continue to do any range checks that you require. TryParse is better than @Bork's suggestion because it is easier to read and avoids the throwing/catching of un-necessary exceptions.

不要一次尝试和验证一次击键。 1)您刚刚发现退格需要更多代码,现在添加对剪切/复制和粘贴的支持,删除键和键入替换选择。代码不太好。 2)它只会使用户感到困惑。或者更糟糕的是,他们尝试输入一个。在您的字段中分隔日期,您可以通过忽略第二个日期将该日期强制为合法数字。他们现在输入了一些完全错误的东西,你的程序也不会告诉他们。文本框的验证事件是这种逻辑应该去的地方。当焦点移动到另一个控件(其CausesValidation属性为true时,它将触发,即使当前控件未处于有效状态,也允许单击取消按钮)。在验证事件中,您可以执行所需的所有检查,并在数据无效时取消事件,并显示您需要的任何消息。要验证值,我建议使用Single.TryParse,然后如果转换成功,您可以继续进行所需的任何范围检查。 TryParse比@ Bork的建议更好,因为它更容易阅读并避免抛出/捕获不必要的异常。

EDIT: Just noticed you are also restricting the length of the entered text. You can do that by setting the MaxLength property of the TextBox.

编辑:刚刚注意到你也在限制输入文本的长度。您可以通过设置TextBox的MaxLength属性来实现。

#5


I think the link below should give you exactly what you're after:

我认为下面的链接应该能够准确地告诉您:

Numeric TextBox

Although it requires a fair amount of code to handle validation on each keypress, it's certainly possible, and the code above seems to handle delete, backspace, copy/pasting etc.

虽然它需要相当数量的代码来处理每个按键的验证,但它当然是可能的,并且上面的代码似乎处理删除,退格,复制/粘贴等。

#6


Or use a regular expression for the tough stuff

或者使用正则表达式来处理棘手的事情

#7


Yeah, or just make that nested if...then block look like this:

是的,或者只是嵌套if ... then块看起来像这样:

If Textbox5.Text.IndexOf(".") > 0 Then
    If Textbox5.SelectionStart > Textbox5.Text.IndexOf(".") Then
        If Textbox5.Text.Length - Textbox5.Text.IndexOf(".") = 3 Then
            If KeyAscii <> System.Windows.Forms.Keys.Back Then e.Handled = True
        End If
    End If
End If