简体   繁体   English

VB.NET 和 Windows Forms 中的文本框验证

[英]TextBox Validation in VB.NET and Windows Forms

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) ie 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

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.试图通过击键来验证击键会让你很头疼。

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.更好的方法是使用支持小数的控件(如果您使用的是基础设施、componentone、devexpress 等)。用户可以获得视觉提示,并且可以做一些简洁的事情,例如单击箭头以推进数字。

If you're using plain old winforms, have a look at the masked edit control.如果您使用的是普通的旧 winform,请查看蒙版编辑控件。

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.让用户完成然后在有任何问题时通知他们会更加用户友好。

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

Or use a regular expression for the tough stuff或者对困难的东西使用正则表达式

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

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. 1) 您刚刚发现退格需要更多代码,现在添加对剪切/复制和粘贴的支持,并且删除键和键入替换选择。 The code is not nice.代码不是很好。
2) It will only confuse the user. 2)它只会让用户感到困惑。 Or worse, they try and type a.或者更糟的是,他们尝试输入 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.文本框的验证事件是这种逻辑应该 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).它会在焦点移动到另一个控件时触发(其 CausesValidation 属性为 true,这允许即使当前控件未处于有效状态也可以单击取消按钮)。
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.为了验证我建议从 Single.TryParse 开始的值,如果转换成功,您可以继续进行所需的任何范围检查。 TryParse is better than @Bork's suggestion because it is easier to read and avoids the throwing/catching of un-necessary exceptions. 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 属性来做到这一点。

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.虽然它需要大量的代码来处理每次按键的验证,但这当然是可能的,并且上面的代码似乎处理了删除、退格、复制/粘贴等。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM