0

I am setting "e.Cancel = true" in _CellValidating event when user inputs invalid value in my DatagridView Cell.

It seems that e.Cancel also prevent user from Closing the form or hitting X button, How can I add exception to that?(Allow user to close the form even e.Cancel is set to true)

John Saunders
  • 160,644
  • 26
  • 247
  • 397
  • Have you tried checking the sender in the event handler and using conditional logic based on the sender? – Kane Jun 18 '12 at 03:13
  • 1
    Please see "[Stack Overflow is not in need of your SEO skills](http://meta.stackexchange.com/a/130208)". – John Saunders Jun 18 '12 at 03:51

1 Answers1

1

I just rigged up a test project based on this scenario, and it seems that the DataGridView's CellValidating event is called before the Form's Closing event; this means that you have no way of knowing, at the time the cell is validated, whether the user has tried to close the form.

Strictly speaking, the correct sequence of events is for the user to either enter valid data in the cell (or cancel the edit by pressing the escape key) before the form will be allowed to close. However, if you want to allow the form to be closed regardless, you can handle the Closing event for the form:

protected override void OnClosing(CancelEventArgs e) {
    e.Cancel = false;
    base.OnClosing(e);
}

This is bad practice, but it will give you the behaviour that you've asked for.

Bradley Smith
  • 13,353
  • 4
  • 44
  • 57
  • Why is overriding the OnClosing a bad practice? – nunespascal Jun 18 '12 at 03:38
  • @nunespascal It's not overriding the method that's bad practice, it's effectively ignoring the value of the `Cancel` property so that it's always `false` - that's bad practice. – Bradley Smith Jun 18 '12 at 04:00
  • This solved my problem. And yeah, it's really bad to do such practice in winforms but it will prevent users(with minimal knowledge of this application) get annoyed if they refused to continue the use of app. Thanks a lot :) – James Howlette Jun 18 '12 at 04:22