Event handling in Dynamic asp.net user Control - asp.net

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 about how to do this?
Anyone have decent idea?

Let's assume this scenario:
You have a shopping cart page.
The shipment control is loaded.
The user clicks on the next button.
--- Postback ---
The shopping cart page is loaded
The shipment control is loaded.
The event 'click' is handled by the shipment control.
The shipment control is disposed.
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

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.

Related

why my user control in asp.net web application fails to load after each postback & loads for first time only

i am using user control in asp.net , it is loading for first time in page load event & later on every post back event it doesn't load at all.
Note. I am adding user control in page_load event in if(!ispostback) condition.
Is there a way to avoid reloading user control every time??
Thanks.
Sorry: You must create dynamically created controls EACH and every time the Page loads, if you "avoid" it there just is no control. PostBack or not, everything you want to use must be created.
Also, please create controls in Page_Init, it belongs there, especially if you're relying on PostBack and ViewState.
Further reading: ASP.NET Page Life Cycle Overview

User Control in Master Page loads first

I have a User Control in a Master Page that calculates quantity of products in the shopping basket and writes to page something like shopping cart(2), showing that you have 2 products.
When you add a product to basket, User Control loads first and then Add method of the page executes because of the page life cycle.
So In order to see the new added product takes effect - shopping cart(3) - i need to refresh the page..
What is the best solution in order to see this after add to cart button is pressed with no refreshing the site.
Do I need to use master page's pre_render event?
Having a look at the ASP.Net page life cycle, you'll find that the LoadComplete (for pages only) and PreRender events are called after the postback handlers.
It should be sufficient to move your shopping cart calculation into the User Control's PreRender event.
Just take care of the actual order of event execution, and call your logic accordingly:
http://msdn.microsoft.com/en-us/library/ms178472.aspx
Normally the Master Page UC should subscribe to an event which is fired by the page whenever an item is added.
Best way of doing is to use the custom Event in user control.
How ever if you don't want to use that, you can use a work around. Simply create a property of user control to show count and updates its value in Add method of that page.

Can't dynamically add Web User Controls

I understand the page lifecycle and how I need to add the dynamic controls on page_init if I want to take advantage of viewstate. And I already have read a lot of topics regarding the issue but it was not very useful.
I have to work with the solution where I have a set of user controls, that inherit one interface and then I add/delete them dynamically to a literal control. I can't load them at once in a page_init because later I have to delete/add them based on user actions. These controls contains a button, and its post back event handler is fired only when I generate this user control at page_init or page_load methods.
So I have to somehow reinitialise/restart lifecycle of the page after needed processing in some Button_Click, (where I update the controls list) events handlers. That is not possible, as I have found. Redirecting to the same page is not a solution, because in the case I will lost my whole viewstate.
So I am stuck, could you please help me with the solution?
It sounds like you could benefit from creating a CompositeControl.
I recently answered a similar question based on dynamically creating textboxes in which I provided a fairly detailed example.
See: Dynamically add a new text box on button click
Hope this helps.
If I'm understanding this correctly, you need to instantiate the dynamic controls to retrieve their view state, but you're relying on the view state to determine how to instantiate the dynamic controls.
You could utilize the ASP.NET Session State? Use the Session State to store the information from which you generate the dynamic controls.
When you handle the button click event, destroy and recreate all of the controls, and then store all the information you need to recreate them again in the Session State.
The next time the page instantiates, the page_init function can check if there's any pertinent info in the Session State, and use this to recreate the controls.

Dynamically created controls are wiped out on button click

I have webform where a set of controls are generated in a Panel control during a SelectedIndexChanged event of a dropdown. That all works fine.
However, when I enter values in those controls and I click on my submit button, the controls are wiped out along with the data I entered.
I can only create the controls in that SelectedIndexChanged event because that's where I get the info to generate the dynamic controls.
What I'd like to do is keep those controls displayed with the data I entered and use the data I entered to do something else (like it happens in WinForms.)
Is this doable?
Thanks!
Every time a postback occurs you are working with a new instance of your page class. Dynamic controls added to the page during a previous postback went to the garbage collector as soon as the page for that postback rendered to the browser. You need to re-create your dynamic controls on every postback.
Save the count of "control-sets" in Session or ViewState, so that you can regenerate them with their appropriate ID's(f.e. appendeded with an indexOfControl) during Page_Init.
Here are some additional informations on:
View State and Dynamically Added Controls *
ASP.NET Page Life Cycle Overview
Extract:
Dynamically added controls must be programmatically added to the Web page on each and every page visit. The best time to add these controls is during the initialization stage of the page life cycle, which occurs before the load view state stage. That is, we want to have the control hierarchy complete before the load view state stage arrives. For this reason, it is best to create an event handler for the Page class's Init event in your code-behind class, and add your dynamic controls there.
This is one of those areas where the attempt to make Webforms look like Winforms fails.
With Webforms, you need to do the whole dance of when to create controls. I believe all your controls will need to be recreated by some time around the end of PageLoad. There might be an event or two after page load that you can use, but generally speaking PageLoad is a safe time to create controls.
Essentially the controls need to be created before ASP.NET populates them with data from ViewState/Browser.

ASP.NET Dynamic Page Controls: Is it possible to bind events AFTER Page.Load?

I have a site that I am currently working on in ASP.NET 2.0 using the usual WebForm stuff and ASP.NET AJAX 1.0. Is it possible to bind an event to a dynamically created control after the Page.Load event?
I have a table <td> element that I am dynamically creating similarly to this code:
' Create Link Button
lnk.ID = String.Format("lnkDetails_{0}", dr("Id"))
lnk.Text = dr("Name").ToString()
lnk.CommandArgument = dr("Id").ToString()
AddHandler lnk.Click, AddressOf DetailsLink_Click
cName.Controls.Add(lnk)
This this code is looped over for each row in a database (and of course more cells are added to the table, including an ImageButton with an event. The events work flawlessly when I execute this code during events leading up to and including Page.Load. I need to be able to fill this table with current data, which is updated during a btnClick Event elsewhere on the page, which occurs after this Page_Load event, so I am populating with old data. If I change this code to Page.LoadComplete, events stop working.
This data is a summary display of various components of an application, things like somebody's name, which when updated on a 'detail' form, updates the database by partial postback (a requirement), then it needs to show the update in this 'summary' section after an update. Currently it takes 2 postbacks to actually see the change in the 'summary' section, so effectively the summary is 1 step behind the changes (clear as mud?)
What would be the best way for me to populate this table with current data (which is available during/after Page.LoadComplete), but still have an event fire when a link is clicked (the event causes an UpdatePanel to display the 'detail' form).
I also have jQuery at my disposal and the usual ASP.NET AJAX methods, also javascript is a requirement for the website, so I do not need to degrade for unsupported browsers.
This is my first ASP.NET web application and need some help figuring out the best way to make this happen (I'm well versed in PHP, Django and the usual ways to do web forms - things like having multiple forms on one page o_O).
Update:
There really isn't a good way to bind control events to controls after Page_Load. The overall architecture of the pages is there is one ASP.NET form encompassing the entire page, there is only 1 aspx page. I am using master pages (however it doesn't have any obvious implications to my issue).
The page is split into a left and right 'pane', the left is a summary of all the data (in an update panel), the right 'pane' has 6 'tabs' implemented each as their own user control, each with several form fields and an update button all in it's own UpdatePanel.
An update on any of these tabs only refreshes the summary panel (UpdatePanel.update()) and its own panel. The 'refreshing' and event binding of dynamic controls of the summary from the db happens during Page_Load and the Update Button event updates db data. (The control event happens after Page_Load). I want to avoid doing a double post to get the summary to update, any thoughts are helpful.
You need to postback the whole page after your data changes in the 'btnClick Event elsewhere on the page'. It sounds like you have an UpdatePanel and it sounds like this is catching the postback of your btnClick event handler. Put the btnClick outside the UpdatePanel or change its triggers so that your btnClick forces a postback/refresh of your data. Or, redesign your table so it's AJAXly-refreshed when you click on btnClick, it's hard to get you more details without knowing more about the structure of your page and controls.
Good luck!
You can bind to an event whenever you want. It's just a simple event after all. But not all places might be suitable because you have to take into account when the event fires. And in most cases this happens between Page_Load and Page_PreRender. That includes the click event on a LinkButton. In general, I would recommend to add your dynamically created controls in the Page_Init stage.
You have to add the controls before Page.Load in order to maintain ViewState between postbacks, so use the OnInit event handler for that.
But once they're added, you should be able to bind event handlers (such as OnClick) at any point during or after the Page.Load... for example in your grid's ItemDataBound (or something like) or in the Page.PreRender.

Resources