You cannot do this using C#.
You have to do this using JavaScript because C# runs on the server and it cannot detect when the browser is being closed; whereas, JavaScript runs in the browser (client side) and can detect when the page is being closed..... Well, ok that's not the full truth, JavaScript can detect when the page is being unloaded.
There is a JavaScript event that is raised whenever the page is unloaded by the browser. It is called the
onbeforeunload event. This method lets you cancel the unload event just in case the user wants to.
The only thing is that this event is raised every time the page is unloaded. This includes when the page is unloaded during full page post backs to the browser. So it does not necessarily mean that the user is closing the window or leaving the page.
Therefore you're going to have to indicate when not to display the "are you sure" message.
When do you not want to display this message?
Well whenever it's one of your controls that cause the unload event to happen of course :)
How do you do this?
Well, that's up to you...but I think it would involve having all of your controls that post back to the server call a method that sets a boolean that indicates it's a valid postback so that the message isn't shown by the method that handles the onbeforeunload event...(hehe run on sentences are fun)
Likewise you need to track if any changes are made.
This means that all of the input controls on the page need to call a method that indicates that the message should be displayed whenever a change to that input control takes place......you'll have to remember this between page post backs too so it's best to store this in a hidden field ;)
That should get you pointed in the right direction.
-Frinny