简体   繁体   English

防止DataGridView自动将编辑提交到数据绑定的对象

[英]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. 通过编辑单元格时自动更新数据源中的基础对象,我的DataGridView变得“有用”。 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. 我假设执行此操作的方法是处理CellValueChanged事件,但是调用事件处理程序时,基础对象已经更新。

Is there a correct way of preventing the DataGridView from doing this? 是否有防止DataGridView这样做的正确方法? 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 我的$ 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. 我完全同意BFree的建议。 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. 如果您不想遵循这种方式,请使用Datagridview.CellValidating事件,该事件在将数据写入基础对象之前发生,甚至允许取消操作。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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