简体   繁体   English

如何将事件处理程序附加到在运行时创建的ASP.NET控件?

[英]How do I attach an event handler to an ASP.NET control created at runtime?

Good morning everybody. 大家早上好。

I have a question connected with controls and event handling. 我有一个与控件和事件处理相关的问题。 Lets say I want to create a LinkButton . 让我们说我想创建一个LinkButton

protected void loadLinkButton()
{
    ContentPlaceHolder content = (ContentPlaceHolder)this.Master.FindControl("MainContent");
    LinkButton lnk = new LinkButton();
    lnk.ID = "lnikBtn";
    lnk.Text = "LinkButton";
    lnk.Click += new System.EventHandler(lnk_Click);
    content.Controls.Add(lnk);
}

Here is the event handler: 这是事件处理程序:

protected void lnk_Click(object sender, EventArgs e)
{
    Label1.Text = "ok!";
}

If I run the loadLinkButton function inside Page_Load everything is ok. 如果我在Page_Load运行loadLinkButton函数一切正常。 But when I try to run the loadLinkButton by clicking simple button, link button is created but event is not handled. 但是当我尝试通过单击简单按钮运行loadLinkButton ,会创建链接按钮但不处理事件。

protected void Button1_Click(object sender, EventArgs e)
{
    loadLinkButton();
}

I there any way to solve it? 我有什么方法可以解决它吗? Or loadLinkButton must always regenerated on Page_Load , Page_init etc. 或者必须始终在Page_LoadPage_init等上重新生成Page_init

It is important to know how ASP.Net determines which events to invoke. 了解ASP.Net如何确定要调用的事件非常重要。 The source of each event is passed using a hidden field: 使用隐藏字段传递每个事件的来源:

<input type="hidden" name="__EVENTTARGET" value="" />

Whenever the page loads, it pulls in the source of the event from that field and then determines which event to invoke. 每当页面加载时,它从该字段中提取事件源,然后确定要调用的事件。 Now this all works great for controls added through markup because the entire control tree is regenerated on every request. 现在这一切都适用于通过标记添加的控件,因为整个控制树都是在每个请求上重新生成的。

However, your control was only added once. 但是,您的控件只添加了一次。 When a Postback occurs, your control no longer exists as a Server control in the tree, and therefore the event never fires. 发生回发时,您的控件不再作为树中的服务器控件存在,因此事件永远不会触发。

The simply way to avoid this is to make sure your Dynamic Controls are added every time the page loads, either through the Page_Init event, or the Page_Load event. 避免这种情况的简单方法是确保每次加载页面时都会添加动态控件 ,无论是通过Page_Init事件还是Page_Load事件。

When working with dynamic controls, I always add the control in Page_Init , because viewstate loading will happen right after Init. 使用动态控件时,我总是在Page_Init中添加控件,因为viewstate加载将在Init之后立即发生。 If you add it to Page_Load, there is a chance that you will lose viewstate. 如果将其添加到Page_Load,则可能会丢失viewstate。 Just make sure you provide a unique control ID. 只需确保您提供唯一的控件ID。

You are right. 你是对的。 This is the expected behavior. 这是预期的行为。 Page_Load and Page_Init would be the events where you should be adding it. Page_Load和Page_Init将是您应该添加它的事件。

That would be because when you click your dynamically generated linkbutton, you do a postback to the server. 那是因为当您单击动态生成的链接按钮时,您会回发到服务器。 There you do an entirely new pageload, but your original buttonclick (that generates the link) never happened now, so the linkbutton is never made, and the event can not be thrown. 在那里你做了一个全新的页面加载,但你原来的buttonclick(生成链接)现在从未发生过,因此链接按钮永远不会发生,并且不能抛出事件。

An alternative is to add the linkbutton you add dynamically, to your page statically, with Visible = false. 另一种方法是使用Visible = false将动态添加的链接按钮静态添加到页面中。 And when you click the other button, make it visible. 当您单击其他按钮时,将其显示为可见。

I am not exactly sure what problem you are facing but you should put the dynamic controls code in Page_Init as suggested by @johnofcross: 我不确定你遇到了什么问题,但你应该按照@johnofcross的建议把动态控件代码放在Page_Init中:

public partial class WebForm1 : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {

        }

        protected void Page_Init(object sender, EventArgs e)
        {
            CreateControls();
        }

        private void CreateControls()
        {
            var lb = new LinkButton();
            lb.Text = "Click Me";
            lb.Click += lb_Click;

            ph.Controls.Add(lb);
            ph.DataBind();
        }

        void lb_Click(object sender, EventArgs e)
        {
            lblMessage.Text = "Button is clicked!"; 
        }
    }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 将事件委托添加到ASP.NET用户控件的事件处理程序 - Add event delegate to event handler of ASP.NET user control 如何为将由PageHandlerFactory处理的ASP.NET中的每个请求添加事件处理程序 - How do I add an event handler for every request in ASP.NET that will be handled by PageHandlerFactory 如何在ASP.NET中添加事件处理程序 - How to add event handler in asp.net 用户控件中的ASP.Net按钮的单击事件处理程序不起作用 - Click Event Handler of ASP.Net Button in User Control is not Working “属性”窗口中的ASP.NET控件事件处理程序出现问题 - Problem with ASP.NET control event handler from the Properties window 在 asp.net C# 中第一次执行该事件后,如何让 RadioButtonList_SelectedIndexChanged 事件处理程序执行? - How do I get the RadioButtonList_SelectedIndexChanged event handler to execute after the first execution of that event in asp.net C#? 如何有条件地控制ASP.NET中控件的可见性? - How do I conditionally control the visibility of a control in ASP.NET? 页面加载后如何向ASP.NET控件添加事件? - How do I add a event to an ASP.NET control when the page loads? 如何给 ASP.Net 自定义控件一个新的自定义事件 - How do I give an ASP.Net custom control a new custom event 如何在asp.net中添加onclick处理程序 - How do I add an onclick Handler in asp.net
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM