Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/csharp/267.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# 如何暂时禁用事件_C#_Winforms_Validation_Events - Fatal编程技术网

C# 如何暂时禁用事件

C# 如何暂时禁用事件,c#,winforms,validation,events,C#,Winforms,Validation,Events,我有一个datagridview,它有单元格验证事件,所以用户必须在离开[0]列之前填充该单元格 private void dataGridView1_CellValidating(object sender, DataGridViewCellValidatingEventArgs e) { if (string.IsNullOrWhiteSpace(dataGridView1.CurrentRow.Cells[0].FormattedValue.ToString()))

我有一个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\u 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\u btn\u单击(对象发送方,事件参数e)
{
dataGridView1.Rows.RemoveAt(dataGridView1.CurrentRow.Index);
如果(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;
}
private void DeleteRow\u btn\u单击(对象发送方,事件参数e)
{
dataGridView1.CellValidating-=dataGridView1\u CellValidating;
dataGridView1.Rows.RemoveAt(dataGridView1.CurrentRow.Index);
如果(dataGridView1.Rows.Count<1)
{
dataGridView1.Rows.Add();
}
dataGridView1.CellValidating+=dataGridView1\u CellValidating;
}
但是它不起作用,我知道为什么,但我不知道如何解决这个问题
感谢您的时间,对我的英语感到抱歉这是因为当您离开单元格以单击“删除”按钮时,但在单击之前,单元格正在进行验证。因此,在click事件处理程序中分离事件将无效

解决方案是仅当行不为空时才显示验证消息。即,如果所有单元格均为空,则不应显示任何验证消息

bool isRowEmpty = dataGridView1.CurrentRow.Cells
    .Cast<Cell>()
    .All(cell => IsNullOrWhiteSpace(cell.FormattedValue.ToString()));
if (isRowEmpty) {
    // validate
}
bool isRowEmpty=dataGridView1.CurrentRow.Cells
.Cast()
.All(cell=>IsNullOrWhiteSpace(cell.FormattedValue.ToString());
如果(是空的){
//证实
}

检查事件处理程序是否附加在多个位置。欢迎使用。另外,由于您是StackOverflow的新手,我想通知您,您可以通过勾选答案旁边的勾号来选择好答案并接受对您帮助最大的答案。在这个网站上,投票或被接受的回答都算作“谢谢”。