Home > Mobile >  Track unsaved changes to the Entity and warn user before closing the Form?
Track unsaved changes to the Entity and warn user before closing the Form?

Time:08-16

I do have a Winform which consists of multiple fields representing the Candidate Entity below. I have an Edit button, which will enable the fields for the user to update this Candidate record and reflect the Entity accordingly. So before closing the Form, I would like to warn the user of unsaved data! Either Save or Cancel? If Cancel is selected reverts the Forms fields data to the previous Entity Data.

Is there an elegant way of doing this mechanism?

public partial class Candidate
    {

        public int Id { get; set; }
        public string FirstName { get; set; } = null!;
        public string? MiddleName { get; set; }
        public string LastName { get; set; } = null!;
        public DateTime? DateOfBirth { get; set; }
        public string? Gender { get; set; }
        public string? Nationality { get; set; }
        public string? Education { get; set; }

    }

CodePudding user response:

There are multiple ways to do this out there, this is a basic example of how to approach the idea. You are basically asking "How do I keep track of the fact that at least one of my properties has changed, and how do I revert it if the user decides against saving".

For your current example, you could add a flag in your class that also gets updated any time a property gets updated.

See this:

            private int id;
            public int Id { 
                get => id;
                set
                {
                    HasChanged = true;
                    id = value;
                }
            }

            public bool HasChanged = false;

Then if the user tries to navigate away, you can check the boolean to see if it needs to be interrupted and decide if you need to restore data.

There are many ways to do this, this is just one example of how you could start to implement it. It's a very common approach in MVVM to have a view model with a dirty flag that can reset if the user chooses. Here is another example on StackOverflow that could help you: MVVM - implementing 'IsDirty' functionality to a ModelView in order to save data

CodePudding user response:

Just do not call SaveChanges(),

  • Related