ASP.NET-动态创建的按钮 [英] ASP.NET - Dynamically created button

查看:71
本文介绍了ASP.NET-动态创建的按钮的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在Webform中添加了一个动态创建的按钮.但是它的点击事件不起作用.谁能解释为什么?

这是我的代码:

  Button save = new Button();save.ID ="btnSave";save.Text =保存";save.Click + =新的System.EventHandler(this.Save_Click);Webform.Controls.Add(保存);受保护的void Save_Click(对象发送者,EventArgs e){Response.Redirect("Default.aspx");} 

它返回到同一页面本身.它不会重定向到Default.aspx.

解决方案

您的代码示例不足以用于诊断,但我会对此进行介绍.

您要在页面生命周期中的什么时候将按钮添加到页面?如果您在PreRender中执行此操作,这就是为什么它不起作用的原因.您应该在初始化期间执行此操作.

更新:

您不能在页面生命周期的Init阶段之后动态创建控件并使它正常工作,除非您每次都以相同的方式创建它.这是因为生命周期如下所示:

Init->加载ViewState->页面加载->事件处理程序-> PreRender.

您正在创建一个按钮,并在倒数第二个阶段为其提供事件处理程序.这意味着该按钮永远不会注册以将其ViewState保存在页面中,因此单击该按钮时不会还原该按钮的所有状态-这意味着您分配的事件处理程序会消失,并且永远不会被调用.

我的建议是在页面上正常创建保存"按钮(而不是动态创建),然后将其设置为Visible ="False".然后,在第一个按钮的Click处理程序上,只需将保存"按钮设置为Visible ="true".

I have added a dynamically created button in my Webform. But its click event is not working. Can anyone please explain why?

This is my code:

    Button save = new Button();
    save.ID = "btnSave";
    save.Text = "Save";
    save.Click += new System.EventHandler(this.Save_Click);
    Webform.Controls.Add(save);

protected void Save_Click(object sender, EventArgs e)
{

    Response.Redirect("Default.aspx");
}

Its coming back to the same page itself. It is not redirecting to Default.aspx.

解决方案

Your code example is not complete enough for a diagnosis, but I'll take a shot at it.

At what point in the page lifecycle are you adding the button to the page? If you're doing it in PreRender, that is why it is not working. You should be doing it during Init.

UPDATE:

You can't dynamically create a control after the Init phase of the page lifecycle and get it to work properly, unless you create it the same way every single time. This is because the lifecycle looks like this:

Init -> Load ViewState -> Page Load -> Event Handlers -> PreRender.

You are creating a button and giving it an event handler during the second last phase. This means that the button is never registered to save it's ViewState with the page, and therefore all state for that button is not restored when it is clicked - meaning that your assigned event handler disappears into thin air, and will never be called.

My suggestion would be to create the Save button normally on the page (not dynamically), and simply set it Visible="False". Then, on the Click handler of your first button, just set your Save button Visible="true".

这篇关于ASP.NET-动态创建的按钮的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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