asp.net中为"动态创建的控件"绑定事件
在线等高手回复!!!!
代码如下:using System;
using System.Data;
using System.Configuration;
using System.Collections;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
public partial class testCase_Button : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
}
protected void Button1_Click(object sender, EventArgs e)
{
Button b = new Button();
b.Text = "Click ";
b.Click += new System.EventHandler(this.ButtonClick);
Panel1.Controls.Add(b);
Panel1.Visible = true;
}
public void ButtonClick(object sender, EventArgs e)
{
Label1.Text = "ButtonClick ";
}
}
<%@ Page Language= "C# " AutoEventWireup= "true " CodeFile= "Button.aspx.cs " Inherits= "testCase_Button " %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN " "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd ">
<html xmlns= "http://www.w3.org/1999/xhtml " >
<head runat= "server ">
<title> Untitled Page </title>
</head>
<body>
<form id= "form1 " runat= "server ">
<div>
<div style= "text-align: center ">
<table style= "width: 340px; height: 309px ">
<tr align=center>
<td style= "width: 100px; height: 4px ">
<asp:Button ID= "Button1 " runat= "server " Text= "Button " OnClick= "Button1_Click " /> </td>
</tr>
<tr align=center>
<td style= "width: 100px; height: 26px; ">
<asp:Panel ID= "Panel1 " runat= "server " Height= "50px " Width= "50px ">
</asp:Panel>
</td>
</tr>
<tr align=center>
<td style= "width: 100px ">
<asp:Label ID= "Label1 " runat= "server "> </asp:Label> </td>
</tr>
</table>
</div>
</div>
</form>
</body>
</html>
运行程序后,会出现一个 "Button1 ",按下这个Button1后会出现另外一个Button2,
为Button2绑定的事件为:b.Click += new System.EventHandler(this.ButtonClick);
如果按下Button2,我希望在Label1中显示 "ButtonClick ".设置断点调试,发现程序根本就没有执行ButtonClick().
急忙等高手帮忙解答!!!!!
希望可以看到修改后的代码,谢谢
[解决办法]
winform这样写是可以的,webform没试过。帮顶~
[解决办法]
楼主的程序,我用WinForm也跑了,同样是不行的。
忘记怎么搞了,前两个月才调查过这个问题的。
。。。。。。
[解决办法]
页面一回发,你添加的控件和事件就都没有了,改用客户端JS来实现
[解决办法]
点button后page_load这些事件都会触发的,之后你的button click事件就没了.
[解决办法]
Button2点击后,重新request一个新的页面,由于动态创建的对象没有保存,当页面重新返回时,Button2已经不存在了,也不能执行它所委托的事件
Button2创建后应保存在session里,在page_load里重新加载到panal里,然后在进行委托就可以了
------解决方案--------------------
动态创建的控件,必须在postback以后再把它创建出来,事件才会执行