简体   繁体   中英

Preventing DataGridView from automatically committing edits to data-bound object

My DataGridView is being 'helpful' by automatically updating the underlying object in the data source when a cell is edited. I want to prevent this and do the updating myself (so that I can perform the update in such a way that it's registered with our custom undo manager).

I assumed that the way to do this was to handle the CellValueChanged event, but the underlying object has already been updated when the event handler is called.

Is there a correct way of preventing the DataGridView from doing this? Perhaps there is a particular event I can handle.

This doesn't answer your question direclty, however I would probably advise you to design your object in such a way that it raises an event before (or after) the value gets changed, so your "undo manager" can be notified. This way your logic isn't tied to the grid. If down the road you'll use this object with something else, you can notify others as well about the value being changed. My $0.02

Code sample:

public class SomeClass
{
    private int myInt;
    public event EventHandler MyIntChanging;
    public event EventHandler MyIntChanged;

    protected void OnMyIntChanging()
    {
        var handler = this.MyIntChanging;
        if (handler != null)
        {
            this.MyIntChanging(this, new EventArgs());
        }
    }

    protected void OnMyIntChanged()
    {
        var handler = this.MyIntChanged;
        if (handler != null)
        {
            this.MyIntChanged(this, new EventArgs());
        }
    }

    public int MyInt
    {
        get
        {
            return this.myInt;
        }
        set
        {
            if (this.myInt != value)
            {
                this.OnMyIntChanging();
                this.myInt = value;
                this.OnMyIntChanged();
            }

        }
    }
}

I fully agree with BFree's suggestion. If you don't want to follow that way, use the Datagridview.CellValidating event that occurs before data is written to underlying object and even allows to cancel the operation.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM