Validating Data In A WinForm


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.

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?]

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.


Please select the form > Set the property CausesValidation to true

Select OK button and again set property CausesValidation to true

and then it will take care of all the validations.

Important points: 1) You must mention e.Cancel=true in all the validating eventhandlers

2) If your buttons are in panels then you must set panels (or any parent control's) CausesValidation property to true


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


First make sure to cancel the validation when any of the textboxes have validation errors. For example:

private void nameTextBox_Validating(object sender, CancelEventArgs e) { if (nameTextBox.Text.Length == 0) { e.Cancel = true; return; } }

Now add the following code to the beginning of the ok button action:

if (!ValidateChildren()) return;

This will trigger the validation event for all controls on the form,


You can also use this simple code. just introducing a simple Boolean variable named hasError can do the job.

public partial class Form1 : Form { private bool hasError; public Form1() { InitializeComponent(); } private void OkBtn_Click(object sender, EventArgs e) { errorProvider1.Clear(); hasError=false; if (ValidateTxt.Text.Length == 0) { errorProvider1.SetError(ValidateTxt, "must have a value"); hasError=true; } if (!hasError) { //Do what you want to do and close your application Close(); } } private void CancelBtn_Click(object sender, EventArgs e) { Close(); } }


  • How to retrieve user entered data inside sessionCreated method
  • why when we write \\n in the file it converts into \\r\\n combination?
  • Java library to escape/clean XML?
  • remove Niqqud from string in javascript
  • How to override UserControl class to draw a custom border?
  • SocketChannel: java.io.IOException: An existing connection was forcibly closed by the remote host
  • django - make datetimefield accept unix timestamp
  • How can I filter REST calls results based on Roles and current user context in Loopback (server side
  • How Can I Prevent Activation For Some ListView Items When The Selection Mode Is MultiChoiceModal?
  • Dependable views in Ember
  • How to override __call__ in celery on main?
  • how do you obtain the address of an instance after overriding the __str__ method in python
  • Send data from edittext to listview
  • Avoid registering duplicate broadcast receivers in Android
  • Caliburn Micro, How to use ContentControl (or display 'sub' ViewModel) using ViewModel Fir
  • Java making confirming exit
  • Perspective projection, 4 points
  • Jquery Mobile pageLoading() Method how does it work?
  • Spring integration inbound-gateway Fire an event when queue is empty
  • Simulate click Geckofx vb,net
  • Thread safety of a fluent like class using clone() and non final fields
  • WPF - CanExecute dosn't fire when raising Commands from a UserControl
  • How to suppress a dialog
  • d3 v4 drag and drop with TypeScript
  • JQuery Internet Explorer and ajaxstop
  • Cancel a live stream “fast motion” catch-up in Flash
  • Disabling Alt-F4 on a Win Forms NotifyIcon
  • Opengl-es onTouchEvents problem or a draw problem? [closed]
  • 'TypeError' while using NSGA2 to solve Multi-objective prob. from pyopt-sparse in OpenMDAO
  • jQuery tmpl and DataLink beta
  • SQL merge duplicate rows and join values that are different
  • Proper way to use connect-multiparty with express.js?
  • How to set the response of a form post action to a iframe source?
  • How get height of the a view with gone visibility and height defined as wrap_content in xml?
  • Linking SubReports Without LinkChild/LinkMaster
  • sending mail using smtp is too slow
  • Busy indicator not showing up in wpf window [duplicate]
  • Why is Django giving me: 'first_name' is an invalid keyword argument for this function?
  • How can I use `wmic` in a Windows PE script?
  • failed to connect to specific WiFi in android programmatically