Confirmation before closing

net windows form application. I have a combo box, a text box and a window close button. Now, if I make changes to the combo box or text box and click the close window button, it should prompt the user to save the changes. If no changes are made (the user simply starts the application, does not make any changes), then he should not ask the user. It should close directly .. How can I do this?

+4
source share
3 answers

One way is to save the bool flag with the name _changed or something like that as a member variable in your form. Then, in the TextChanged event of the TextBox and the SelectedIndexChanged event of the ComboBox, you simply set _changed = true.

Then, shortly before closing the form, you ask the user if _changed is true.

Edit:

If you have many TexBox controls on the form, you can connect them all to one TextChanged event handler. Then, no matter what TextBox text has changed, _changed will be set to true.

Then do the same with multiple ComboBox controls and one SelectedIndexChanged event.

If you really have a lot of controls, instead of manually connecting them manually, you can even write a method that recursively passes through the Controls collection of your form and intercepts each type of control to the corresponding event handler. Then you can reuse this method in more than one form to save a lot of time and money on maintenance, since when you add new controls, they will be automatically taken care of.

+1
source

An easy way to do this is to add the dirty member to the form, which I set to true whenever something changes, and then validates it whenever the form closes.

+4
source

Override the OnClosing method of your form (or attach to the close event). In the handler, check the changes and display a message box to the user. If you do not want the form to close, set e.Cancel to false before returning.

+4
source

Source: https://habr.com/ru/post/1312173/


All Articles