如何为动态创建的按钮创建onClick eventHandler
目前,我正在为学生宿舍做一个项目,现在我必须实施一些关于学生的搜索策略。当用户点击.aspx页面中的另一个服务器按钮时,我必须动态创建一个按钮,因此我必须创建新创建的按钮的onclick事件处理程序。 我使用的代码片段是:
protected void btnsearchByName_Click(object sender, EventArgs e) { TextBox tbsearchByName = new TextBox(); Button btnsearchName = new Button(); tbsearchByName.Width = 250; tbsearchByName.ID = "tbsearchByName"; tbsearchByName.Text = "Enter the full name of a student"; btnsearchName.ID = "btnsearchName"; btnsearchName.Text = "Search"; btnsearchName.Click += new EventHandler(this.btnsearchName_Click); pnlsearchStudents.Controls.Add(tbsearchByName); pnlsearchStudents.Controls.Add(btnsearchName); } protected void btnsearchName_Click(object sender, EventArgs e) { lblsearch.Text = "btnsearchName_Click event fired in " + DateTime.Now.ToString(); }
这里,问题是新创建的eventHandler不会被触发。 我已经浏览了这个网站,看了几个问题和答案,也经历了页面生命周期,他们都说动态按钮应该在Init或Pre_init上,但我的问题是我必须在点击另一个按钮时创建它,怎么可能呢?
您需要在每次回发时添加按钮的单击处理程序。
您可以在页面加载时在搜索学生面板中查找按钮,或者尝试使用页面OnInit()方法在创建时添加处理程序。
另请查看:
动态添加的ASP.NET按钮单击处理程序被忽略
在这里: asp.net动态按钮与事件处理程序
在这里: asp:Button Click事件没有被触发
(所有这些都给出了类似的建议)
试试这个http://msdn.microsoft.com/ru-ru/library/system.web.ui.webcontrols.button.command(v=vs.90).aspx
btnsearchName.Command += new CommandEventHandler(this.btnsearchName_Click);
btnsearchName.CommandName = "Click";
您需要重新创建按钮并每次都附加事件处理程序。 为此,创建一个按钮列表并将其保存在会话中。 在页面加载时,浏览列表并每次创建按钮
public Button create_button() { btnsearchName.ID = "btnsearchName"; btnsearchName.Text = "Search"; btnsearchName.Click += new EventHandler(this.btnsearchName_Click); return btnsearchName; } public TextBox create_textbox() { TextBox tbsearchByName = new TextBox(); Button btnsearchName = new Button(); tbsearchByName.Width = 250; tbsearchByName.ID = "tbsearchByName"; tbsearchByName.Text = "Enter the full name of a student"; return tbsearchByName; } protected void btnsearchByName_Click(object sender, EventArgs e) { TextBox tbsearchByName = create_textbox(); Button btnsearchName = create_button(); //add to panels pnlsearchStudents.Controls.Add(tbsearchByName); pnlsearchStudents.Controls.Add(btnsearchName); //add to session List
我不确定,但可能你必须像这样覆盖OnInit()方法。
protected override void OnInit(EventArgs e) { base.OnInit(e); }
您只需要在jquery代码的就绪状态下添加此代码,它也可以用于动态按钮
$(document).ready(function(){ $('input#tbsearchByName').click(function(){ // code goes here }); });