设置Checked in event后,如何防止CheckChanged触发?

时间:2018-06-02 12:17:33

标签: c# events

我在CheckedChanged事件处理程序中有这段代码:

private void cbLoadStock_CheckedChanged(object sender, EventArgs e) {
        if (cbLoadStock.Checked == false &&
            MessageBox.Show("Are you sure you want to do that?",
            "Warning", MessageBoxButtons.YesNo, MessageBoxIcon.Exclamation) == DialogResult.Yes) {

            cbLoadStock.Checked = true;
        } else {
            cbLoadStock.Checked = false;
        }
    }

但是,当我点击“是”时,它会将Checked设置为true,从而导致再次调用处理程序。

如何设置复选框才能设置?

1 个答案:

答案 0 :(得分:1)

正如我在评论中提到的,这应该做的工作:

private void cbLoadStock_CheckedChanged(object sender, EventArgs e) {
        cbLoadStock.CheckedChanged -= cbLoadStock_CheckedChanged;
        if (cbLoadStock.Checked == false &&
            MessageBox.Show("Are you sure you want to do that?",
            "Warning", MessageBoxButtons.YesNo, MessageBoxIcon.Exclamation) == DialogResult.Yes) {

            cbLoadStock.Checked = true;
        } else {
            cbLoadStock.Checked = false;
        }
        cbLoadStock.CheckedChanged += cbLoadStock_CheckedChanged;
    }