views:

291

answers:

2

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.

+2  A: 

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();
            }

        }
    }
}
BFree
Deep down I was probably afraid of this answer. This is probably the correct way of doing things, but it's also likely to be significantly more work to implement than the quick hack I was hoping for. Thanks though.
spatulon
A: 

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.

Daniel Brückner