Question

In my Window, I have created a form, contains Id, Code, Name and Values camps, they is bonded on Product.Id, Product.Code, Product.Name and Product.Value, where in my constructor

public partial class ProductEdit : Window, INotifyPropertyChanged
{
    // SystemContext is a DbContext
    private SystemContext db = App.db;

    private Product _product;
    public Product Product 
    {
        get
        {
            return _product;
        }
        set
        {
            _product = value;
            OnPropertyChanged("Product");
        }
    }

    public ProductEdit()
    {
        this.InitializeComponent();
        Product = new Product();

        this.DataContext = this;
    }

    private void btSave_Click(object sender, RoutedEventArgs e)
    {
        db.Products.Add(this.Product);
        try
        {
            db.SaveChanges();
            this.Close();
        }
        catch (Exception ex)
        {
            MessageBox.Show(ex.Message);
        }
    }

    private void btReset_Click(object sender, RoutedEventArgs e)
    {
        // What can I do in here for cancel change?
    }

}

What can I do for cancel changed values?


Solution after @har07 answer

    private void btResetar_Click(object sender, RoutedEventArgs e)
    {
        // Used when is new register
        if (Product.Id == 0)
            Product = new Product();
        else    // Used when is editing register
        {
            db.Entry(Product).State = System.Data.Entity.EntityState.Unchanged;
            Product = db.Pasteis.First(r => r.Id == Product.Id);
        }
    }

If no set entry state to Unchanged and try get same register, it will get with edited values
If no get same register after unchanged register, it will not update UI values

Was it helpful?

Solution

If you meant to cancel all changes in Product, all of it, as if you just opened a new ProductEdit Window, why not simply create a new Product :

private void btReset_Click(object sender, RoutedEventArgs e)
{
    Product = new Product();
}

As what you did in constructor. Previously created Product object hasn't been added to DataContext, hence will not be saved later when user click Save button. This seems to be too straightforward, I suspect I missed something in your situation (._.)? Is there any problem with this approach which I can't see it?

UPDATE :

Assuming that you get Product from DbContext instead of create it new, then you want to cancel all edit made so that Product property values remain as it originally stored in DbContext, you can try to do it by changing Product's State property as follow :

db.Entry(Product).State = EntityState.Unchanged;

See this blog post about Rejecting changes to entities in EF 4.1.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top