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

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

问题描述

你能告诉我下面的代码有什么问题吗?

  Panel div = new Panel(); 
按钮btn1 = new Button {Text =Delete,CommandArgument =argument,ID =remove};
按钮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); //其中ph_plan是用户控件中的占位符

protected void btn_click(object sender,EventArgs e)
{
按钮btn =(Button)sender;
if(btn.ID ==remove)
//做这个
else
//做那个
}

上面的代码是在用户表单中点击一个按钮后发生的。应该创建2个新的按钮,分配事件。确实,它创建了按钮,但当我点击它们什么也没有发生。我猜这个事件是无法注册的。我在这里做错了什么?

解决方案

这是因为页面是一个无状态的类,一旦它呈现一切,它就被破坏。因此,一旦您有回发,此信息将丢失,您的页面类不知道按钮的事件,因为动态按钮不是 aspx 文件。



您需要维护一个可以在会话中创建的动态控件的集合,以便在回发后重新创建它们。 这里的示例。


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
}

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?

解决方案

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.

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天全站免登陆