验证WinForm中的数据 [英] Validating Data In A WinForm
问题描述
我在WinForms应用程序中创建了一个对话框.它具有许多文本框和确定/取消"按钮.当用户单击确定"时,我只希望在所有条目均有效的情况下关闭对话框.我可以看到如何分别使用每个控件的"Validating"事件来执行此操作.那样就好.但是,这些似乎仅在控件失去焦点时才会触发.但是,对话框中的空白文本框也是无效的输入,这意味着用户可能永远不会专注于该控件.我希望仅在单击确定"后验证所有控件.
I have created a dialog box in my WinForms application. This has many text boxes and ok/cancel buttons. When the user clicks ok, I only want the dialog box to close if all entries are valid. I can see how to do this with the "Validating" events for each control separately. That is fine. But these only seem to fire when a control loses focus. However, empty text boxes in my dialog are also invalid input which means the user may never have focused on that control. I would prefer to just validate all controls on clicking OK.
尽管如此,我还是不知道该怎么做.覆盖确定"按钮的onclick似乎没有停止窗口关闭的选项.Form IsClosing事件通过设置Cancel = true来完成.但这似乎无法区分是单击确定"还是取消"按钮.显然,如果单击了取消"按钮,我不在乎验证,并且无论如何都希望关闭表单.
I can't work out how to do this though. Overriding the onclick of the OK button doesn't seem to have an option for stopping the window from closing. The Form IsClosing event does by setting Cancel = true. But this doesn't seem to be able to distinguish between whether the OK or Cancel button is clicked. Obviously if the cancel button is clicked I don't care about validation and want to allow the form to close regardless.
执行此操作的最佳方法是什么?]
What is the best approach for doing this?]
更新:我已经在窗体和确定"按钮上都将CausesValidation设置为true,但是当我单击确定"按钮时,不会触发我的验证事件.我提到了这一点,因为建议将其作为下面的解决方案.
Update: I already had CausesValidation set to true on both my form and ok button but my validation event does not get fired when I click the ok button. I mention this as it was suggested as a solution below.
推荐答案
请选择表单>将属性 CausesValidation
设置为 true
Please select the form > Set the property CausesValidation
to true
选择确定按钮,然后再次将属性 CausesValidation
设置为 true
Select OK button and again set property CausesValidation
to true
然后它将处理所有验证.
and then it will take care of all the validations.
重要要点:1)您必须在所有验证事件处理程序中提及 e.Cancel = true
Important points:
1) You must mention e.Cancel=true
in all the validating eventhandlers
2)如果按钮在面板中,则必须将面板(或任何父控件的) CausesValidation
属性设置为 true
2) If your buttons are in panels then you must set panels (or any parent control's) CausesValidation
property to true
3)在失去焦点之前验证射击.在按下Enter的同时导致默认按钮为点击",但不会将焦点移到该按钮上按钮,因此,如果将表单的AcceptButton属性设置为确定"按钮,则不会触发任何验证事件
3) Validate fires just before loss of focus. While pressing Enter will cause the default button to Click, it doesn't move the focus to that button, hence no validation event will be fired if you have set forms AcceptButton Property to OK button
这篇关于验证WinForm中的数据的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!