【问题标题】:How to Stop DataGridView editing after checked cell?检查单元格后如何停止 DataGridView 编辑?
【发布时间】:2017-04-20 21:32:42
【问题描述】:

我在DataGridView 上使用ContexMenuStrip 删除了一些行,但它不能正常工作。

如果我每次检查 3 行,在选择 ContexMenuStrip 后它只会删除 2 行。当我在没有ContexMenuStripButton)的情况下执行此代码时,它可以正常工作。

当我看到我理解当前行正在编辑但没有完成的行为时。双击当前行停止编辑后,我的ContexMenuStrip 工作正常。

查看CheckBox后如何停止编辑?

【问题讨论】:

    标签: c# checkbox datagridview contextmenustrip


    【解决方案1】:

    选择并编辑单元格后,DataGridView 属性 IsCurrentCellDirty 将设置为 True。如果您在 DataGridViewCheckBoxCell 上的此状态更改时捕获事件处理程序,则可以调用 DataGridView.EndEdit() 立即完成这些更改。

    this.dataGridView1.CurrentCellDirtyStateChanged += DataGridView1_CurrentCellDirtyStateChanged;
    
    private void DataGridView1_CurrentCellDirtyStateChanged(object sender, EventArgs e)
    {
        if (this.dataGridView1.IsCurrentCellDirty && this.dataGridView1.CurrentCell is DataGridViewCheckBoxCell)
        {
            this.dataGridView1.EndEdit();
        }
    }
    

    进一步解释:

    在幕后,每当您编辑当前单元格时,DataGridView.IsCurrentCellDirty 都会更新。上面的第一行代码允许您将自己的事件处理程序 (DataGridView1_CurrentCellDirtyStateChanged) 附加到 CurrentCellDirtyStateChanged 事件。因此,每当单元格变脏时,幕后都会调用基本级别的事件,然后也会调用您的方法。如果没有该行,您的方法将不会被调用。 += 运算符是附加你的方法到事件的调用链。

    例如,添加以下处理程序:

    this.dataGridView1.CurrentCellDirtyStateChanged += DataGridView1_Example1;
    // this.dataGridView1.CurrentCellDirtyStateChanged += DataGridView1_Example2;
    this.dataGridView1.CurrentCellDirtyStateChanged += DataGridView1_Example3;
    
    private void DataGridView1_Example1(object sender, EventArgs e)
    {
        Console.WriteLine("Example 1");
    }
    
    private void DataGridView1_Example2(object sender, EventArgs e)
    {
        Console.WriteLine("Example 2");
    }
    
    private void DataGridView1_Example3(object sender, EventArgs e)
    {
        Console.WriteLine("Example 3");
    }
    

    当脏状态改变时,您将看到以下输出。注意第二个事件处理程序被排除在外:

    // Example 1
    // Example 3
    

    【讨论】:

    • 我使用了你的代码,它工作正常。但我不明白需要 {this.dataGridView1.CurrentCellDirtyStateChanged += DataGridView1_CurrentCellDirtyStateChanged;}
    【解决方案2】:

    code proposed by OhBeWise 有一个小问题。它适用于鼠标点击。但是,如果您使用 Space 键切换复选框,则如果不先手动切换当前单元格,您将无法再次切换复选框。稍作改动即可使用:

    private void DataGridView1_CurrentCellDirtyStateChanged(object sender, EventArgs e)
    {
        if (this.dataGridView1.IsCurrentCellDirty && this.dataGridView1.CurrentCell is DataGridViewCheckBoxCell)
        {
            this.dataGridView1.EndEdit();
    
            DataGridViewCell currentCell = this.dataGridView1.CurrentCell;
    
            this.dataGridView1.CurrentCell = null;
            this.dataGridView1.CurrentCell = currentCell;
        }
    }
    

    【讨论】:

      猜你喜欢
      • 2010-12-07
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-09-25
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多