Create Dynamic Controls using retrieved data [Asp - Vb .Net] - asp.net

I'm trying to create multiple controls by using retrieved data from query, but preventing them from dissapearing on postback, allowing me to get and mantain their values, the problem I have is that I cannot create them on Init because the number of controls, their IDs, and other properties are only known after user selects an item on menu.
Page loads a Menu with all its items and values (Data dependent), plus, a button is loaded too
User clicks a item on menu.
Selected value is used to perform a query by using a Dataset (This happens inside a function which is called from Menu_ItemClick event).
Retrieved data from query is used to determine how many controls must be created (2, 4, 6, etc.). Each control has its unique ID, which is given according to data.
Controls are created and placed into a Panel (named p).
Now controls are visible and available for editing (RadioButtons, TextAreas)
User clicks on button to save information from dynamic controls into a Database
Problems I'm facing
Controls dissapear on postback when clicking button, because they weren't created on Init.
Placing button on UpdatePanel to prevent whole page postback, makes dynamic controls not accesible when trying this:
For Each c In p.Controls
...
Next
The only control it gets is a single Literal control (Controls count is 1), as if other controls didn't exist.
Thank you in advance.

When you wrote "Controls dissapear on postback when clicking button, because they weren't created on Init", did you mean to say that "Controls dissapear on postback when clicking button, because they weren't re-created on Init"? If not, then that is likely a root cause of your problem - dynamically-created controls must always be recreated in response to a PostBack (cf. ASP.NET dynamically created controls and Postback). There may be other issues as well, as dynamic controls in Web Forms can provide a lot of challenges as your scenario gets more involved - here's one article that lays out many of them under various scenarios http://www.singingeels.com/Articles/Dynamically_Created_Controls_in_ASPNET.aspx (e.g., if the user can re-select from the DropDownList to generate a different set of dynamic controls). The canonical reference on all of this is http://msdn.microsoft.com/en-us/library/ms178472.aspx.
Now, on PostBack you'll need some way to ascertain which controls were dynamically created so they can be dynamically re-created. As such, you'll need to store somewhere whatever information allowed you to dynamically create the controls. Since ViewState isn't available in Page_Init and there can be other issues introduced when using sessions, my suggestion is to simply declare a HiddenField that contains that state information. In Page_Init, you'll then need to get the HiddenField's value from Request.Form (since the value of your HiddenField won't be loaded until after Page_Init from ViewState) and go from there to re-create your controls.
My final suggestion: try getting everything working with a regular Panel first and then try and introduce the UpdatePanel - no need to over-complicate the problem at first.

Related

How to avoid re-binding data controls with ASP.Net Dynamically Loading a User Control

The overall problem is that I have a web application that has many hidden controls that are shown and hidden based on user rights or based on particular actions within the main page. Because there are so many hidden controls and the combination of each of these control's databinds paired with the sheer size of the resulting rendered HTML, the page is too slow to load. We can of course move the databinds to only occur on the show of the controls but this only addresses half of the problem. We are attempting to address both by Dynamically loading the usercontrols. As we all know the problem with this approach is that when dynamically loading the control, it must be re-added to the page on every subsequent request. So anytime say a dropdown in selected on the dynamic child control that causes an action (like OnClick event), it has to reload the child control, which by itself isn't bad but you also have to rebind all the controls on the page or your databound controls will all be empty. So is there anyway to get around having to rebind all of the controls with every load of the child control? I know that for simple things like a textbox I could save the viewstate and the text would persist between requests and reloading the control, but say the child control has a grid with several hundred rows of data after it is bound, how do I persist that when reloading the child control? I can post a small example if needed.
use Update Panel, i think i will call to server only for updated data not whole page or control.

Dynamic Controls and Postback

I have a Panel. Now in that panel, i'm adding controls. It is getting added and displayed.The problem is when the page is posted back.I know the controls have to be binded again in the panel. But lets say if the user has entered some value in the dynamic created text box. Its is getting lost..
I have done this before by storing the data from the controls in session.
Every time you dynamically add a control, store the current data entered into the controls in session or viewstate for example, and then rebind on postback. Not the most elegant solution but it worked. I take it this is a webforms question?
Add dynamic control click
Save current form data
On page_load load the data from viewstate into the controls
Make sure that the controls get the same ID each time (for ex. by specifying an ID explicitly)
and you should add the dynamic controls on Page.Init so they can participate in the page's life-cycle.
There's an article on 4guysfromrolla.com, Dynamic Web Controls, Postbacks, and View State

ASP.Net Web Form + Ajax Data lost on post back. Possible cause ? Ajax or changing visible property

I have two Repeater controls, each hosted in a user control. Both user controls are contained in the same aspx page. Only one User Control is visible at any one time. The repeaters are comprised of checkboxes, and text boxes for user input.
The aspx page is configured with an Ajax ScriptManager; and contains several Ajax UpdatePanels. These UpdatePanels result in partial page post backs when text is changed in a textbox control in controls on the aspx page (this is not the behaviour for the Repeaters in the User Controls). Through use of several AsyncPostBackTriggers, various controls contained in the other UpdatePanels on the page have their content refreshed in response to the partial page post backs they are configured be notified about.
Depending on a radio button group selection, I set the visible property to true or false – as appropriate for the User control containing a repeater control. The Repeater control is then populated with data using databinding. All of this works.
However, when the Submit button is clicked, the Repeater control contains no data.
Given that I am not dynamically adding the Controls containing the Repeater controls (but using Visible true / false). I would have thought that the State of the fields and the data in the visible control would be preserved during the post back.
The User Controls are contained within the UpdatePanel that contains the Submit Button.
I have explicitly Enabled View state without any effect.
Am I correct in assuming that I should not have to do any explicit handling of data changes the user makes (via client side script and manipulation of an Data Structure Representing the Repeater Data); and the View State should maintain the data I need to access on the server when submitted?
I do not believe that it is the User Control visible state changes that are causing the issue because when the page is initially loaded on of the User controls is populated with dummy rows (so it displays).
I am suspicious that because the visible state of the controls is changed during partial page post back, that the Page View State ends up with no knowledge of the User Control and therefore cannot track its data (or changes).
I have investigated a lot of similar sounding posts but so far do not feel that I have come across a solid explanation that can help me understand and fix the issue.
Hopefully someone can help.
I must be the only person who was unaware of the finer points of DataBind() method; be it called on a specific control being bound to data; or on the page itself. I hope the below helps others who find themselves in a position where data binding appears to be inexplicably lost'.
My problem was that my page was pretty complex. It has several User Controls on it. The problem was that in these User Controls, I was calling Page.DataBind() in the Page_Load event handler to 're-bind' the page data on PostBacks. This resulted in the Repeater control located on another User Control, to lose its data binding.
Removing the Page.DataBind method call from each of the User Controls on the Page_Load event handler method resolved the problem. It had nothing to do with Update panels / refreshes etc.

Failed to load viewstate when dynamically loading different controls

I have an aspx page which is loading some controls dynamically on postback (ie when a click event happens) and adding them to a placeholder. Depending on what is clicked a different set of controls needs to be loaded.
This works perfectly the first time, but when I clear the placeholder's controls and attempt to dynamically load a different set of controls I get the following error:
"Failed to load viewstate. The control tree into which viewstate is being loaded must match the control tree that was used to save viewstate during the previous request."
This happens even if I do ViewState.Clear().
Is there a way to do this?
Yuriy Solodkyy explains it well here: Dynamically Created Controls in ASP.NET
When dynamically creating controls you must ensure that every control you create has an unique id.
I think what is happening here is that you are naming your controls like: Control1, Control2, Control3.
And perhaps when you click to create a different set of controls you might give the same name to a different type of object, lets say Control1 was first created like a Textbox and when you click its a checkbox.
Without seeing the code is tough to tell why ViewState.Clear() is not working, but if you are trying to clear the viewstate you don't need a postback, you can try requesting a new page and pass the arguments on the querystring instead of a postback. This will be faster too as you don't have to send the ViewState information back to the server.

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