当我单击表单上的X(关闭按钮)时如何防止验证被触发 [英] How to prevent validating from being fired when I click X (Close button) on the form

查看:293
本文介绍了当我单击表单上的X(关闭按钮)时如何防止验证被触发的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这是Winform C#问题。我有一个带有验证事件侦听器的文本框,用于验证文本框的内容。说,文本框不接受负值。我只听验证事件,所以默认情况下,文本框的AutoValidate属性为EnablePreventFocusChange,这对我来说完全没问题。

This is a winform C# question. I have a textbox with a validating event listener to validate the content of the textbox. Say, the textbox doesn't accept negative values. I only listen to validating event so by default, the textbox's AutoValidate property is EnablePreventFocusChange, which is totally fine for me.

问题是,当我单击X按钮时,在表单的右上角,我不希望触发验证,因为无论如何我都在关闭表单。我怎样才能做到这一点?没有控件将CauseValidation设置为false,如果有关闭按钮,我可以这样做。非常感谢。

The problem is, when I click the X button on the right top corner of the form, I don't want the validation to be fired because I am closing the form anyway. How can I do this? There is no control to set CauseValidation to false, which I can do if there is a closing button. Thank you very much.

推荐答案

嗯,我认为要做的唯一方法是设置表单上的AutoValidate 为假,并在控件中手动处理验证。该表单具有 .Validate() .ValidateChildren()方法,请仔细阅读以下内容执行验证。要手动处理它,您将需要在控件失去焦点时进行监听-如果验证失败,则可能需要重新关注有问题的控件。

Hmmm, the only way I would think to do it is to set AutoValidate on the form to false and handle validation in the controls manually. The form has .Validate() and .ValidateChildren() methods, read up on these as they are what you need to perform validation. To handle it manually, you will need to listen for when a control is losing focus - if validation fails you then need to perhaps re-focus the offending control.

使其形式为 ControlBox = false; 删除X按钮。

Alternatively, make the form ControlBox = false; to remove the X button.

更新:另外,您可以再次使用成员变量来测试是否验证(即,表单是否关闭)。您不能使用 FormClosing 事件来执行此操作,因为该事件会在验证后触发,但是您可以通过 WndProc 检测到表单关闭。这篇文章中提供了代码:

Update: Alternatively again you can use a member variable to test whether to validate or not (ie, whether the form is closing or not). You cannot do this using the FormClosing event as this fires after the validation, however you can detect form closing via WndProc. Code is provided in this post:

http://technoblot.wordpress.com/2006/09/08/winforms-causesvalidation-not-working-a-workaround/

一种较少涉及的解决方法。

A slightly less involved workaround.

这篇关于当我单击表单上的X(关闭按钮)时如何防止验证被触发的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆