views:

87

answers:

3

Hi I am using c# .net windows form application. I have a combo box and a text box and a close window button. Now If I make any change in the combo box or textbox and click on the close window button, it should prompt the user to save the modifications.. If no modification are made ( The user will just run the application, doesnt make any modification) then it should not prompt the user. It should close directly.. How can I do this?

+4  A: 

An easy way to do it is by adding a dirty member to the form, which I set to true whenever anything changes and then check it whenever the form is closing .

ho1
A: 

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

Then, just before your form closes you prompt the user if _changed is true.

Edit:

If you have many TexBox controls on the form, you could hook them all up to the same TextChanged event handler. Then, no matter which TextBox's text changed, _changed will be set to true.

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

If you really have many controls, rather than hooking each up manually, you could even write a method that recursively loops through the Controls collection of your form and hooks each type of control up to the appropriate event handler. Then you could reuse that method in more than 1 form to save you lots of time and maintenance, as when ever you add new controls, they will automatically be taken care of.

Jacques Bosch
Thank you.. Its working.. I have another doubt. here I have only a textbox and a combobox and I will make _changed to true in the SelectedIndexChanged of combo and TextChanged event of textbox. What if I have many more controls. Should I make _changed to true in every control Or is there any option such that I can apply it when there is any change in any of the controls in that form. I mean to say can I apply to the form.. i.e if there are any changes made in the form _changed must be true
saeed
I edited my answer according to your followup question.How about a vote up if you think mine is the most helpful answer. ;)
Jacques Bosch
+4  A: 

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

munissor