[英]Preventing DataGridView from automatically committing edits to data-bound object
通過編輯單元格時自動更新數據源中的基礎對象,我的DataGridView變得“有用”。 我想防止這種情況並自己進行更新(以便我可以通過在我們的自定義撤消管理器中注冊的方式來執行更新)。
我假設執行此操作的方法是處理CellValueChanged事件,但是調用事件處理程序時,基礎對象已經更新。
是否有防止DataGridView這樣做的正確方法? 也許有一個我可以處理的特殊事件。
這不能解決您的問題,但是我可能建議您以這樣的方式設計對象:在值更改之前(或之后)引發一個事件,以便可以通知您的“撤消管理器”。 這樣,您的邏輯就不受網格約束。 如果您將來會將此對象與其他對象一起使用,則可以將更改的值也通知其他人。 我的$ 0.02
代碼示例:
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的建議。 如果您不想遵循這種方式,請使用Datagridview.CellValidating事件,該事件在將數據寫入基礎對象之前發生,甚至允許取消操作。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.