自定义事件 - button.click [英] custom event - button.click

查看:70
本文介绍了自定义事件 - button.click的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

你能告诉我这段代码有什么问题吗?

would you please tell me what is wrong with this code?

if (button1.Click = true)
{
    this.label1.Text = "custom event";
}





错误是:

事件... control.click可以只有左边的+ =或 - =



我这里有一个自定义事件,有几个按钮可以导致。

但是在代码中我必须知道哪个按钮导致了自定义控件。



谢谢大家



Jibesh添加的代码块[/ Edit]



Error is:
the event "...control.click" can only apear on the left hand side of += or -=

I have here a custom event which several buttons can cause.
But in the code I have to know which button caused that custom control.

thank you all

Code block added by Jibesh[/Edit]

推荐答案

Click是一个事件 - 所以你不能将它与布尔值进行比较。



你真正需要做的是在 sender 参数中查看事件处理程序,该参数标识按下的按钮:

Click is an event - so you can''t compare it to a boolean value.

What you actually need to do is look inside the Event handler at the sender parameter, which identifies the button that was pressed:
private void AnyOfMyButtons_Click(object sender, EventArgs e)
    {
    Button wasClicked = sender as Button;
    if (wasClicked != null)
        {
        Console.WriteLine(wasClicked.Text);
        }
    }

例如,将在单击的按钮上打印文本。

Will print the text on the button that was clicked, for example.


问题在于: button1.Click = true Button.Click [ ^ ]是一个事件。你不能这样测试它。你必须为它分配一个事件处理程序,就像上面页面上的例子一样。

但我无法想象你是怎么做到这一点的,因为所有IDE都创建了事件处理程序如果你选择了这个活动,或者只是设计模式中的按钮上的DoubleClick。



我觉得你以错误的方式对待某事。该方法的其余部分(特别是标题)是什么,这段代码片段位于?
The problem is here: button1.Click = true. The Button.Click[^] is an event. You can''t test it this way. You have to assign an event handler to it, like in the example on the page above.
But I can''t imagine how you came to this, since all IDE''s create the event handler for you if you choose the event, or simply DoubleClick on the button in design mode.

I have the feeling you treat something in the wrong manner. What is the rest (especially the header) of the method, this code snippet resides in?




button1.Click是一个事件。如果你想创建一个自定义事件,你必须添加以下代码。

此代码将为您生成一个运行时按钮控件,并可以对其单击事件执行所需的操作。

Hi,
"button1.Click" is an event.If you want to create a custom event you have to add the following code.
This code will generate a run-time button control for you and can perform desired operation on its click event.
private void Form1_Load(object sender, EventArgs e)
       {
           Button btn = new Button();
           btn.Text = "custom button";
           this.Controls.Add(btn);
           btn.Location = new Point(10,10);//you can add the control on your desired location.
           btn.Click += new System.EventHandler(btn_Click);
       }
       private void btn_Click(object sender, EventArgs e)
       {
           //add your code here.
          
       }


这篇关于自定义事件 - button.click的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆