简体   繁体   English

第二个事件处理程序不会从按钮触发

[英]Second eventhandler won't trigger from button

I have 2 buttons. 我有2个按钮。 The first button gets drawn from the code behind. 第一个按钮从后面的代码中提取。 The second button gets drawn when the first button is clicked. 单击第一个按钮时会绘制第二个按钮。 This works perfectly. 这非常有效。 When I add a event when the second button gets clicked this event won't be triggered. 单击第二个按钮时添加事件时,不会触发此事件。 As you can see in the code below there is a btnTwo_click function. 正如您在下面的代码中看到的那样,有一个btnTwo_click函数。 If I put a breakpoint on this function the program won't even break. 如果我在此函数上设置断点,程序甚至不会中断。 Is there a way to trigger this event from the code behind (not using java script)? 有没有办法从后面的代码中触发此事件(不使用java脚本)?

Here is the code, I actually use this system in a table. 这是代码,我实际上在表中使用这个系统。 But this simple code has the same problem in the end. 但是这个简单的代码到底有同样的问题。

public partial class _Default : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {
        ImageButton btn = new ImageButton();
        btn.Command += new CommandEventHandler(btnOne_Click);
        form1.Controls.Add(btn);
    }

    void btnOne_Click(object sender, EventArgs e)
    {
        ImageButton btn = new ImageButton();
        btn.Command += new CommandEventHandler(btnTwo_Click);
        form1.Controls.Add(btn);
    }

    void btnTwo_Click(object sender, EventArgs e)
    {
        Label lblTest = new Label(); //BREAKPOINT
        form1.Controls.Add(lblTest);
    }
}

只需将此行移至Page_Load事件即可运行;)

btn.Command += new CommandEventHandler(btnTwo_Click);

You have to add the second button on the Page_Load or Page_Init method of Page life cycle: 您必须在Page生命周期的Page_Load或Page_Init方法中添加第二个按钮:

eg 例如

protected void Page_Load(object sender, EventArgs e)
{
    ImageButton btn = new ImageButton();
    btn.Command += btnOne_Click;
    form1.Controls.Add(btn);

    ImageButton btn2 = new ImageButton();
    btn2.Command += btnTwo_Click;
    btn2.Visible = false;
    form1.Controls.Add(btn2);
}

void btnOne_Click(object sender, EventArgs e)
{
    // Your second button 
    form1.Controls[2].Visible = true;
}

void btnTwo_Click(object sender, EventArgs e)
{
    ImageButton btn2 = (ImageButton)sender;
    // Do something
}

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

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