填充时如何停止CellValueChanged触发?

Dua*_*ane 5 c# vb.net datagridview

我有一个包含几个DataGridView的表单.在程序运行时,它们将以编程方式清除和填充.这是基于用户在表单中在其中一个DataGridView中更改的单元格.用户更改单元格会触发清除和重新填充所有DataGridViews,包括与之交互的DataGridViews.

所以现在问我的问题.每次DataGridViews被清除并以编程方式重新填充时,我是否可以避免触发CellValueChanged?相反,它只应在用户编辑表单中的单元格时触发.

我试图寻找一个没有成功的答案,所以我希望这不是一个重复的问题.

Eug*_*kal 7

我怀疑你可以阻止CellValueChanged事件被触发,除了删除你的处理程序(事件仍将被触发,但不会有任何处理程序):

private dgv_ThatCausesChanges_CellValueChanged(object sender, EventArgs e)
{        
    this.otherDGV.CellValueChanged -= this.dgv_OtherDGVCellValueChanged;

    try // To make sure that handlers are reinstatiated even on exception thanks @Steve
    {       

         // Change other DGVs
    }
    finally
    {    
         this.otherDGV.CellValueChanged += this.dgv_OtherDGVCellValueChanged;
    }
}
Run Code Online (Sandbox Code Playgroud)

或者作为替代解决方案,只需添加一些标志,将在每个处理程序中检查:

private bool IsChanging;

private dgv_ThatCausesChanges_CellValueChanged(object sender, EventArgs e)
{
    this.IsChanging = true;

    try // To make sure that handlers are reinstatiated even on exception thanks @Steve
    {  

        // Change other DGVs
    }
    finally
    {    
        this.IsCHanging = false;
    }
}

private dgv_OtherDGVCellValueChanged(object sender, EventArgs e)
{
    if (this.IsChanging)
        return;

    // Handle changes
}
Run Code Online (Sandbox Code Playgroud)