如何创建一个onClick事件处理程序用于动态创建按钮 [英] How to create an onClick eventHandler for a dynamically created button

查看:207
本文介绍了如何创建一个onClick事件处理程序用于动态创建按钮的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

目前,我做了学生宿舍的一个项目,现在我要实现约students.Here一些搜索策略,我必须动态地当上了另一台服务器按钮,用户点击.aspx页面中,因此我创建一个按钮要创造新创建的按钮的onclick事件处理程序。我使用了code-片段是:

Currently, I am doing a project for students' hostel and now I have to implement some search strategies about students.Here I have to create a button dynamically when the user clicks on the another server button in .aspx page and accordingly I have to create the onclick event handler for the newly created button. The code-snippet that I used is:

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();

    }

在这里,问题是新创建的事件处理程序不列入被解雇。我已经通过这个网站了,看着几个问题和答案,并通过页面生命周期了,他们都说,动态按钮应该是init或pre_init,但我的问题是我当另一个创建它按钮被点击,它怎么可能?

Here, the problem is newly created eventHandler doesnot get fired. I have gone through this site and looked several questions and answers and also gone through the page life-cycle and they all say that the dynamic button should be on Init or Pre_init, but my problem is I have to create it when another button is clicked, how can it be possible?

推荐答案

您需要添加单击处理程序在每次回发的按钮。

You need to add the click handler for the button on every postback.

您可以查找按钮,在搜索学生面板上的页面加载或尝试在页面的OnInit()方法添加处理程序的创建时。

you could look for the button in the search students panel on page load or try the page OnInit() method to add the handler when its created.

也检查这里:

<一个href=\"http://stackoverflow.com/questions/11245808/dynamically-added-asp-net-button-click-handler-being-ignored\">Dynamically添加ASP.NET按钮单击处理程序被忽略

在这里:
<一href=\"http://stackoverflow.com/questions/7713242/asp-net-dynamically-button-with-event-handler\">asp.net动态与事件处理程序按钮

在这里:
ASP:按钮的Click事件不会被解雇

(所有这些给出类似的建议)

(all of which give similar suggestions)

这篇关于如何创建一个onClick事件处理程序用于动态创建按钮的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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