简体   繁体   English

C#按钮仅在第二次单击时触发

[英]C# Button is firing only on the second click

I have done a simple windows form. 我做了一个简单的窗体。 My button is firing only on the second click. 我的按钮仅在第二次点击时触发。 Why is that ? 这是为什么 ?

private void button1_Click(object sender, EventArgs e)
{
    //button1.Enabled = false; will disable the button before the event is fired
    this.button1.Click += new System.EventHandler(this.dosomething);
}

private void dosomething(object sender, System.EventArgs e)
{
    listBox1.Items.Add("Initializing :" + cart + "...");
    this.button1.Click -= new System.EventHandler(this.dosomething);
}

Can some one explain this. 有人可以解释一下。

That's exactly what you told it to do. 这正是你告诉它要做的。

   this.button1.Click += new System.EventHandler(this.dosomething);

This line adds a handler to the click event, which will run for all future clicks. 此行为click事件添加了一个处理程序,该事件将针对以后的所有点击运行。

As other said you hook up the event only on the first click. 正如其他人所说,你只在第一次点击时挂钩事件。

Place this line in the form_load event 将此行放在form_load事件中

this.button1.Click += new System.EventHandler(this.dosomething);

Because you're hooking it up on the first click: 因为您在第一次点击时挂了它:

this.button1.Click += new System.EventHandler(this.dosomething);

so it's going to take at least one click to get the dosomething method to fire. 因此,至少需要点击一下才能启动dosomething方法。

One other problem with this approach is that you could end up hooking this event handler up more than once if an exception is thrown. 此方法的另一个问题是,如果抛出异常,您最终可能会多次挂起此事件处理程序。 I know you're removing it in the dosomething event, but it would really be better to just hookup this event in the constructor. 我知道你在dosomething事件中删除了它,但是在构造函数中连接这个事件真的会更好。

What you are trying to do is to remove the bound event from the button after the button was clicked. 您要做的是在单击按钮后从按钮中删除绑定事件。 You can call the event directly by: 您可以通过以下方式直接致电活动:

private void button1_Click(object sender, EventArgs e)
{
    dosomething(null, null)
}

If you want button to work only 1 time, you can unsuscribe to click event. 如果您希望按钮只能工作一次,则可以取消订阅click事件。

private void button1_Click(object sender, EventArgs e)
{
    DoSomething();
    button1.Click -= button1_Click;
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM