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

后端 未结 5 1900
爱一瞬间的悲伤
爱一瞬间的悲伤 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: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:

    
    

    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.

提交回复
热议问题