Displaying "Are you sure" confirmation on Cancel button

Displaying "Are you sure" confirmation on Cancel button

Old forum URL: forums.lhotka.net/forums/t/9323.aspx

jtrotman posted on Wednesday, August 04, 2010

This is kind of a trivial thing, but I wanted to see if anyone had any thoughts on this.

When a user clicks the Cancel button on a screen where they have been editing an object, my application pops up a MessageBox that says something like "You have unsaved changes. Are you sure you want to cancel?"  I use the IsDirty property to decide whether or not to display this.

I just realized that if the user clicks the New button to create a new object/record, and then Cancels without making any changes - they get the "You have unsaved changes..." message even though they really don't.  I now see that IsDirty (more specifically IsSelfDirty) defaults to True on a new object. 

At the top of p. 266 of the 2008 C# book, Rocky says "The IsSelfDirty property defaults to true because a new object's field values won't correspond to values in the database."  This is true, but I would argue that it would be more useful if the default was False because:

IsNew = True & IsDirty = True means a new item needs saving

IsNew = True & IsDirty = False means there is a new item, but there's nothing to save yet because the user hasn't done anything that needs saving (in which case I wouldn't display the "Are you sure..." confirmation if the user cancels in this state.

Thoughts?  Also, does anyone have a better way of doing this as the framework is now?  I can't imagine I'm the only one doing this.

Jeff Trotman



RockfordLhotka replied on Wednesday, August 04, 2010

You are certainly not alone. But you can override the default behavior by overriding MarkNew() in your custom base class:

protected override void MarkNew()

That switches the behavior so new objects are not dirty.

jtrotman replied on Thursday, August 05, 2010

That works for me (overriding MarkNew).

Thanks for the quick reply (as well as all of your effort - both with the books and the time you spend here.)


Jav replied on Wednesday, August 04, 2010

Creating a new record introduces changes in the object graph.  So the mesage, "You have unsaved changes...." is correct.

On creation of a new object, the behavior IsNew = True & IsDirty = True is the correct bevavior.  Now the user has two choices: either Save the new object (with or without manual changes); or Undo the creation of the new object.

Copyright (c) Marimer LLC