Event handling in Dynamic asp.net user Control
Web Forms or ASP.NET MVC? I will count web forms ...
Try using CompositeControl. If there is data binding, you can use DataBoundCompositeControl. In the CreateCHildren method, you dynamically create your controls, add them to the child collection. Below is an example of a fairly complex DataBoundCompositeControl I, created once (with event handling on inner child controls):
It's actually really hard to get it right. Just remember to restore all your child controls every time and save the state of the control so you can recreate everything correctly.
You will be restoring everything twice by return mail (and once on the first GET). Once, to recreate the controls in their previous state, and to process the changes a second time after data binding and event handling.
source to share
Let's assume this scenario:
- You have a shopping cart page.
- The shipping control is being loaded.
- The user clicks on the next button.
--- Postback ---
- Shopping cart page loaded
- The shipping control is being loaded.
- The 'click' event is handled by the submit control.
- Shipment control sent.
- Payment management is loading.
You can store a variable in a session instance to determine which control to load.
On the PageInit page of the cart page, you retrieve the Session variable and load the appropriate control (steps 1 and 2). Make sure you do this in PageInit so that ASP.NET can fire events.
In the event handler in the shipping control, you then update the session variable (step 3).
On the Page_LoadComplete page of the cart page, you submit the dispatch control (step 4) and load the payment control (step 5).
Scott Mitchell wrote a great article about this scenario: http://scottonwriting.net/sowBlog/posts/3962.aspxsource to share