Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

I am looking to prompt the user to save data when they close a form window in a winforms application. I can't figure out how to trigger the prompt to the user, should they click the red box at the top right corner of the form.

My application currently has a boolean flag, that is set to True on textchanged event. So I will only need to check for the boolean value in whatever event is trigger by the red box.

Any advice?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
250 views
Welcome To Ask or Share your Answers For Others

1 Answer

You need to handle the FormClosing event. This event is raised just before the form is about to be closed, whether because the user clicked the "X" button in the title bar or through any other means.

Because the event is raised before the form is closed, it provides you with the opportunity to cancel the close event. You are passed an instance of the FormClosingEventArgs class in the e parameter. By setting the e.Cancel property to True, you can cancel a pending close event.

For example:

Private Sub Form_Closing(ByVal sender As Object, ByVal e As FormClosingEventArgs)
    If Not isDataSaved Then
        ' The user has unsaved data, so prompt to save
        Dim retVal As DialogResult
        retVal = MessageBox.Show("Save Changes?", YesNoCancel)
        If retVal = DialogResult.Yes Then
            ' They chose to save, so save the changes
            ' ...
        ElseIf retVal = DialogResult.Cancel Then
            ' They chose to cancel, so cancel the form closing
            e.Cancel = True
        End If
        ' (Otherwise, we just fall through and let the form continue closing)
    End If
End Sub

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...