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

后端 未结 5 1901
爱一瞬间的悲伤
爱一瞬间的悲伤 2021-01-19 10:51

Good morning everybody.

I have a question connected with controls and event handling. Lets say I want to create a LinkButton.

protected          


        
相关标签:
5条回答
  • 2021-01-19 11:04

    When working with dynamic controls, I always add the control in Page_Init, because viewstate loading will happen right after Init. If you add it to Page_Load, there is a chance that you will lose viewstate. Just make sure you provide a unique control ID.

    0 讨论(0)
  • 2021-01-19 11:07

    It is important to know how ASP.Net determines which events to invoke. 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.

    0 讨论(0)
  • 2021-01-19 11:12

    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.

    An alternative is to add the linkbutton you add dynamically, to your page statically, with Visible = false. And when you click the other button, make it visible.

    0 讨论(0)
  • 2021-01-19 11:13

    You are right. This is the expected behavior. Page_Load and Page_Init would be the events where you should be adding it.

    0 讨论(0)
  • 2021-01-19 11:23

    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:

    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!"; 
            }
        }
    
    0 讨论(0)
提交回复
热议问题