views:

2609

answers:

2

Hi all,

I Have a page, where I want to dynamically add asp.net user controls. The scenario is that we want that on specific event of a control, It disposes itself and loads another control in the page.

I am not able to have solution how to do this?

any one have decent Idea, Please help..

Thanks Singh Ajay

A: 

Webforms or ASP.NET MVC? I'll assume webforms...

Try using a CompositeControl. If there is databinding involved you can use the DataBoundCompositeControl. In the CreateCHildren method you dynamically create your controls add add them to the child collection. Here is an example of a fairly complicated DataBoundCompositeControl I created once (with event handling on inner child controls):

Scaffolding Control

This is actually a really hard thing to get right. Just remember to rebuild all of your child controls everytime and to store the state of the control so you can recreate everything properly.

You will rebuild everything twice on postbacks (and once on the first GET). Once to recreate the controls to their previous state and the second time to process the changes after databinding and event handling.

It's tricky, I hope this helps!

justin.m.chase
A: 

Hi Singh Ajay,

Let's assume this scenario:

  • You have a shopping cart page.
  • The shipment control is loaded.
  • The user clicks on the next button.

--- Postback ---

  1. The shopping cart page is loaded
  2. The shipment control is loaded.
  3. The event 'click' is handled by the shipment control.
  4. The shipment control is disposed.
  5. The payment control is loaded.

You can store a variable in the Session instance to determine which control needs to be loaded.

In the PageInit of the shopping cart page you retrieve the Session variable and load the corresponding control (step 1 & 2). Make sure you do this in the PageInit in order for ASP.NET to fire the events.

In the event handler in the shipment control, you then update the Session variable (step 3).

In the Page_LoadComplete of the shopping cart page you dispose the shipment control (step 4) and load the payment control (step 5).

Scott Mitchell has written a great article about this scenario: http://scottonwriting.net/sowBlog/posts/3962.aspx

mathijsuitmegen