Edit

Share via


CancelEventArgs.Cancel Property

Definition

Gets or sets a value indicating whether the event should be canceled.

public bool Cancel { get; set; }

Property Value

true if the event should be canceled; otherwise, false.

Examples

The following example uses CancelEventArgs and a CancelEventHandler to handle the FormClosing event of a Form. This code assumes that you have created a Form with a class-level Boolean variable named isDataSaved. It also assumes that you have added a statement to invoke the OtherInitialize method from the form's Load method or the constructor (after the call to InitializeComponent).

// Call this method from the constructor of your form
void OtherInitialize()
{
    Closing += Form1_Closing;
    // Exchange commented line and note the difference.
    isDataSaved = true;
    //this.isDataSaved = false;
}

void Form1_Closing(object sender, CancelEventArgs e)
{
    if (!isDataSaved)
    {
        e.Cancel = true;
        _ = MessageBox.Show("You must save first.");
    }
    else
    {
        e.Cancel = false;
        _ = MessageBox.Show("Goodbye.");
    }
}

Applies to