vb.net 最好使用 Validating 或 Leave 事件来验证文本框数据?

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

Better to use Validating or Leave event to validate textbox data?

vb.netvalidationtextbox

提问by Taylor K.

When coding validation logic for a VB .NET textbox, which event handler is better to use: Validatingor Leave?

在为 VB .NET 文本框编码验证逻辑时,哪个事件处理程序更适合使用:ValidatingLeave

From what I understand, they both occur at the same time. However, according to this article: MSDN: Control.Leave Event, the Leave event occurs right before the validating event. This would initially make me think I would rather use the Leave event, as it occurs first.

据我了解,它们都是同时发生的。但是,根据这篇文章:MSDN: Control.Leave Event,Leave 事件发生在验证事件之前。这最初会让我觉得我宁愿使用 Leave 事件,因为它首先发生。

However, for code readability, it would make sense to place all validation code in the Validating event.

但是,为了代码可读性,将所有验证代码放在 Validating 事件中是有意义的。

So, which is the better option, in terms of both efficiency and industry-standards?

那么,就效率和行业标准而言,哪个是更好的选择?

回答by Hans Passant

You should alwaysuse the Validating event, it was made to support validation. If not to prevent the focus change then at least for the CausesValidation property. Which you set to False on, say, the Cancel button of a dialog. No point in validating anything when the user decides to dismiss the dialog.

您应该始终使用 Validating 事件,它被用来支持验证。如果不是为了防止焦点更改,那么至少对于 CausesValidation 属性。例如,在对话框的取消按钮上将其设置为 False。当用户决定关闭对话框时,验证任何内容都没有意义。

回答by prprcupofcoffee

The Validatingevent is designed for validation. If the text isn't valid, set e.Cancel = True, and focus stays on the text box. Leaveis just a notification.

Validating事件是为验证而设计的。如果文本无效,请设置 e.Cancel = True,焦点将停留在文本框上。Leave只是一个通知。