Home > Net >  Detecting which button was clicked when closing a winform?
Detecting which button was clicked when closing a winform?

Time:09-21

I have this event handler in my winform:

private void SaveToDXF_FormClosing(object sender, FormClosingEventArgs e)
{
    // Make sure the user has selected at-least one layer
    if (listBoxLayers.SelectedItems.Count == 0)
    {
        _AcAp.Application.ShowAlertDialog("Please select one or more layers.");
        e.Cancel = true;
    }
}

Originally I was using the OK button click handler but I quickly found out that there did not seem to be a way to cancel out of actually closing the form. Then I read on SO a suggestion to use FormClosing. This works fine but ...

If the user closing the form by pressing the Cancel button this event still fires. That makes sense. But I only want to perform this validation check and cancel closing the form if they click the OK button.

How do we do this?

CodePudding user response:

Sounds like you can check the this.DialogResult in the closing handler: it will be different depending which button was clicked (whatever you set as the DialogResult in the properties grid).

e.g. "don't do the check if they are cancelling" could be like

if (this.DialogResult != DialogResult.Cancel && listBoxLayers.SelectedItems.Count == 0)

If you have more checks to do it might be simple to just "if cancelling then return" as the event handler first line

  • Related