动态分配在C#中asp.net按钮事件 [英] Dynamically assign button events in c# asp.net

查看:155
本文介绍了动态分配在C#中asp.net按钮事件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

您能告诉我有什么错如下code?

Can you please tell me what's wrong with the following code?

        Panel div = new Panel();
        Button btn1 = new Button { Text = "Delete", CommandArgument = "argument", ID = "remove" };
        Button btn2 = new Button { Text = "Insert", CommandArgument = "argument2", ID = "insert" };

        btn1.Click += new EventHandler(btn_click);
        btn2.Click += new EventHandler(btn_click);

        div.Controls.Add(btn1);
        div.Controls.Add(btn2);

        ph_plan.Controls.Add(div); // where ph_plan is a placeholder in the user control

protected void btn_click(object sender, EventArgs e)
{
    Button btn = (Button)sender;
    if(btn.ID == "remove")
        // do this
    else 
        // do that
}

在code在用户窗体上的一个按钮,点击之后出现上述。它应该创建具有指定事件2新的按钮。事实上,它创建的按钮,但是当我点击他们没有任何反应。我猜的事件不能被注册。我在做什么错在这里?

The code above occurs right after a click on a button in the user form. It is supposed to create 2 new buttons with events assigned. Indeed, it creates the buttons but when I click them nothing happens. I guess the events cannot be registered. What am I doing wrong here?

推荐答案

这是发生的原因是因为是一个无状态类,一旦它呈现的一切,这是销毁。因此,一旦你有一个回传,该信息将丢失,你的类没有按钮的事件的知识,因为动态按钮是不是 ASPX 文件。

The reason this is happening is because Page is a stateless class and once it renders everything, it is destroyed. Therefore, once you have a postback, this information is lost and your Page class has no knowledge of the button's events since the dynamic buttons were not part of the aspx file.

您需要维护您已经创建,可能在一个会话中的动态控件的集合,让他们可以在回发后重新创建。有 href=\"http://www.$c$cproject.com/kb/aspnet/dynamiccontrolsByLeon.aspx\">了。

You need to maintain a collection of the dynamic controls that you've created, possibly in a session, so that they can be recreated after a postback. There's an example of it here.

这篇关于动态分配在C#中asp.net按钮事件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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