【问题标题】:How to disable event temporarily如何暂时禁用事件
【发布时间】:2015-02-24 23:24:04
【问题描述】:

我有具有单元格验证事件的 datagridview,因此用户必须在离开该单元格之前填充列 [0] 上的单元格

private void dataGridView1_CellValidating(object sender, DataGridViewCellValidatingEventArgs e)
    {
        if (string.IsNullOrWhiteSpace(dataGridView1.CurrentRow.Cells[0].FormattedValue.ToString()))
        {
            MessageBox.Show("Please fill this field");
            e.Cancel = true;
        }

    }

即使该行上的所有单元格都是空的,我也想使用按钮删除行,但是每次我单击 DeleteRow_btn 时都会显示验证消息

private void DeleteRow_btn_Click(object sender, EventArgs e)
        {
            dataGridView1.Rows.RemoveAt(dataGridView1.CurrentRow.Index);
            if (dataGridView1.Rows.Count < 1)
            {
                dataGridView1.Rows.Add();
            }
        }

我已经尝试过了

private void DeleteRow_btn_Click(object sender, EventArgs e)
{
        dataGridView1.CellValidating -= dataGridView1_CellValidating;
        dataGridView1.Rows.RemoveAt(dataGridView1.CurrentRow.Index);
        if (dataGridView1.Rows.Count < 1)
        {
            dataGridView1.Rows.Add();
        }
        dataGridView1.CellValidating += dataGridView1_CellValidating;
}

但它不会工作,我知道为什么,但我不知道如何解决这个问题 谢谢你的时间,对不起我的英语

【问题讨论】:

  • 检查事件处理程序是否附加在多个位置。
  • 不客气。另外,由于您是 StackOverflow 的新手,我想通知您,您可以通过勾选答案旁边的勾号来为好的答案投票并接受对您帮助最大的答案。在本网站上,点赞或接受的答案都算作“感谢”。

标签: c# winforms validation events


【解决方案1】:

这是因为当您离开单元格以单击删除按钮时,单元格正在验证,但在单击发生之前。因此,在 click 事件处理程序中分离事件将无效。

解决方案是仅当行不为空时才显示验证消息。 IE。如果所有单元格都是空的,则不会出现验证消息。

bool isRowEmpty = dataGridView1.CurrentRow.Cells
    .Cast<Cell>()
    .All(cell => IsNullOrWhiteSpace(cell.FormattedValue.ToString()));
if (isRowEmpty) {
    // validate
}

【讨论】:

    猜你喜欢
    • 2018-09-28
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-03-18
    • 1970-01-01
    • 1970-01-01
    • 2010-12-27
    • 1970-01-01
    相关资源
    最近更新 更多