Speakslowly 2018-12-07 07:30 采纳率: 0%
浏览 1769

关于C#触发事件,没有点击也会触发点击事件

在做项目时候遇到一个让我很头疼的问题,
我写了一个radiobutton 和一个button,两个控件都做了点击事件,
当我点击button时候会跳进去radiobutton的点击事件中。
大概情况是这个样子的。但是以下代码不会跳出我上边所描述的问题,
但可以完全模拟,同事在第一次试的时候也出现了同样的问题,但是后来又没有了

private void button3_Click(object sender, EventArgs e)
        {
            bool b = false;
            MessageBox.Show("button");

         }

        private void radioButton1_Click(object sender, EventArgs e)
        {
            MessageBox.Show("radiobutton");
        }

我在点击Button的时候执行完Bool b=false;后就直接跳到radioButton1_Click事件中。
最后项目改用了checkBox控件不会出现以上现象,虽然项目是完成了,但是想问问这个原因是为什么,感谢大神

  • 写回答

1条回答 默认 最新

  • 你知我知皆知 2024-08-07 10:02
    关注

    以下回答参考 皆我百晓生券券喵儿 等免费微信小程序相关内容作答,并由本人整理回复。

    这个问题是因为在点击按钮时,你已经执行了RadioButton的Click事件,并且在Click事件中返回了False,这导致了RadioButton的Click事件永远不会被调用。因此,当你再次点击按钮时,实际上是在点击之前就已经发生了Click事件。

    为了解决这个问题,你可以考虑在按钮的Click事件中检查是否已经发生了Click事件:

    private void button3_Click(object sender, EventArgs e)
    {
        bool b = false;
    
        // Check if the Click event has already been fired
        if (!b) {
            // Perform your logic here
            MessageBox.Show("button");
        } else {
            // If the Click event was already fired, you can do something else
            // For example, clear the flag and try to fire the Click event again
            b = true;
            MessageBox.Show("button");
        }
    }
    

    或者,如果你不希望按钮每次点击都会触发Click事件,你可以使用CancelEventArgs来取消事件处理程序的默认行为:

    private void button3_Click(object sender, CancelEventArgs e)
    {
        bool b = false;
    
        // Check if the Click event has already been fired
        if (!b) {
            // Perform your logic here
            MessageBox.Show("button");
        } else {
            // If the Click event was already fired, you can do something else
            // For example, clear the flag and try to fire the Click event again
            b = true;
            MessageBox.Show("button");
        }
    }
    

    这样,当按钮再次被点击时,它将按预期的那样执行Click事件。

    评论

报告相同问题?