Maintain the state of dynamically added user control on postback? - c#

I have a user control that contains only a text box and on another form I add this user control dynamically, a user can add the user control many times. I use a session variable to recreate the user control (maybe this approach doesn't sound cool). After recreating the control the value of the textbox disappears, obviously. Is there any solution to maintain the state of the user control on postback?

If you add dynamic controls back to the control during the correct Page Life Cycle event(PreInit) they will maintain their state through the IPostBackDataHandler interface.
PreInit - Create or re-create dynamic controls.

I've had the same problem in the past.
What I did was give the dynamically-added control an ID, and made sure it retained that ID also on postback (in my case, I kept all the information in the session, and re-created the controls).
Once the postbacked control has the same ID as as before, Microsoft did magic and refilled the controls with the pre-postback values.

Use the object cache. Add the usercontrol into the cache and retrieve it when you need it.
You can see a nice example of how this works at: ASP.net-Tutorials Cache and Object Cache.
I am also learning asp.net now and found that quite a nice explanation. I also used the Microsoft Library

Every server control that inherits the IPostBackDataHandler interface has a LoadPostData method that processes the postback data. When control is implemented by a class (page, form, placeholders, controls etc), that class calls the LoadPostData method and passes the posted data and key to maintain control states.
All you need to do is to re-instantiate / reinitialize dynamic controls before or within page load event each and every time during postback and add this control to page / forms / placeholders. Then the posted data will automatically be assigned to the control by calling LoadPostData method by the parent control.
Check this article to learn how to write code for dynamic control -
How to maintain dynamic control events, data during postback in asp.net

Related

Can I call an event method of a parent from within an UpdatePanel on a UserControl?

I have the following scenario that I need to implement.
I have a GridView with a list of records. When a user selects a record, a pop-over screen appears within the browser showing the contents of the record. The contents are rendered from a UserControl, and within the UserControl there is an UpdatePanel that is used for loading/reloading data as it is manipulated and saved.
What I need to occur is that after each save on my UserControl, the GridView on the parent page needs to refresh as to reflect any changes on the record being shown in the pop-over editor control.
My plan is to setup an event on my UserControl that the parent page will subscribe too. When a save operation is executed from within the UserControl, it will call the event, and the parent page should update itself.
However, since the UserControl operates within an UpdatePanel, and is only doing a partial-postback, I am suspect that my events will not work properly.
Should this work as I hope or will I need to find another way of telling my parent page to refresh the master GridView after a record is saved?
If I need to to call an update in a different manner, what is the best approach for this scenario? I ask because I'd rather not build-out some complex saving/updating operation only to find out that I've made a few miss-assumptions and need to re-code the whole update and reload process.
I have done that before I just don't remember exactly how as I haven't been working with Web Forms in a little while. You have the right idea. The event will get raised on the parent page but you will have to do another PostBack/Partial PostBack afterwards to update the grid from the event handler on the parent. Also you will have to make sure the properties on the UpdatePanel have been set up right.
Another option is doing a full postback when you close the PopUp. If the popup is big enough that it prevents the user from seeing the grid it wont make a difference whether the record on the grid is updated when the Modal is closed rather than when the data is saved.

The text of a textbox in a dynamic control is not set on post back due to UniqueID change

As the title suggests, we are having issues getting the correct text value of a Textbox after a post back.
Context:
The Textbox is called textbox_registration
The Textbox is in a dynamically loaded control.
The dynamic control is recreated every post back and has its data set in the OnInit event.
The dynamic controls are within a PlaceHolder inside an UpdatePanel.
It is expected that the value posted in the form will then be present in the Text property of the Textbox. The first form submission is fine, then it gets weird. The UniqueID of textbox_registration changes in every subsequent submission, breaking the expected value stored in the Text property. The following is an example of the UniqueIDs of the Textbox.
ctl00$CollapsableSidebar$panel_editAsset$ctl01$textbox_registration
ctl00$CollapsableSidebar$panel_editAsset$ctl02$textbox_registration
My theory is that when the dynamic control it loaded in init again it avoids a collision with the previous instance of the Textbox by changing the generated UniqueID, then when the second post back occurs the ID has to be different, and thus corrupting the ViewState initialisation between the init and load methods.
This is very irritating, because looking in the Request.Form collection I can see the correctly posted value.
How can I retrieve the posted value for textbox_registration.Text?
Edit 1:
Just to clarify textbox_registration is a normal static ASP Textbox within a UserControl that we have loaded dynamically.
Edit 2:
To outline the scenario, the source code has been stripped down to the following files:
Item Page, a page to display items.
Edit Pane, a custom UserControl on the Item Page that is used to load the dynamic controls.
Dynamic Control, an example of a dynamic item editing control loaded into the Edit Pane.
IEditItemPanel, an interface that the edit controls must implement.
Try setting ClientIDMode property when you create your TextBox control
textbox_registration.ClientIDMode = ClientIDMode.Static;
Then when you want to retrieve the text
var textBox = (TextBox)this.Form.FindControl("textbox_registration");
var textBoxText = textBox.Text;
After investigating the issue, it was a logical error causing the issue.
Because the edit control was loaded dynamically it was important that the control was loaded for post backs by the end of OnInit or up to OnLoad as long as the item was loaded in the control before Controls.Add() was called.
With this knowledge, the OnInit event was investigated closely in the dynamic control. It was being called twice on the post backs! A logic error! This caused the controls to be created twice and the posted form values corresponded to the controls created in the first OnInit call. Therefore, the second OnInit call generated different UniqueIDs for the controls. When the ViewState was restored the controls did not exist.
The solution was to make sure the control is created properly every post back like the first time it is created. The first time didn't make a duplicate control, so neither should the second!
Turns out a look back at the 'Dynamic Controls Basics 101' was needed.
This link 'Dynamic Controls Made Easy in ASP.Net' finally made the solution click into focus.

Adding ASPX components from Code behind using C#

I have a requirement which adds html/aspx components from code behind. The components can be either Check box or Radio button and options for them comes from the Database.
So what is the best approach to do this. Is user control helps here?
You should generally determine and add such controls via the page OnInit overload or Page_Init event, and be sure you do it on all requests, including postbacks.
Define local variables to hold the objects you may create (it could be a List<> if you don't know how many will exist ahead of time), and instantiate them as any other object, set their properties, and then add them to the Controls collection of the container item they should be in; By default, they will be added to the end of the container, but you can Insert them instead of Add if you like.
Assuming you re-create them like this every time, and do it during Init, you can then access them - including viewstate, if applicable - from the Load event/overload.

How to access Form controls on Postback from Dynamically built form

I'm adding controls at run-time to the Page Form object.
Each control has an Id.
On postback, I want to be able to access these controls and their values.
Currently, when I do a postback, the form has no controls in the Form.Controls Collection.
How can I rectify this?
Is this only possible if you add the controls to the page every time the page loads?
Dynamically added controls need to be added with every page load or else they will be lost.
However the viewstate of these controls can be maintained as long as they always get added with the same ID.
I believe you have to add the controls dynamically in order to access them on postback. So if you add a textbox dynamically, your event handler can't retrieve its value unless you add it again.
EDIT: One workaround I used was to add a predetermined set of server controls to the page and then use JavaScript to hide/show those elements. You avoid postbacks and you avoid the unnecessary tom-foolery associated with retrieving values from dynamically added server controls. Of course, this limits you to a predefined number of controls.
This was a big pet peeve of mine with ASP.NET web forms and is a factor in my decision to explore ASP.NET MVC - no more viewstate/postback mess.

UserControl - accessing textbox within UserControl within a web form

I am using c#.net
I have different views within my webform, these all generally display different information except for three textboxes (arrival / seen / depart time). To try and cut down on code, I have created a UserControl which contains these three textboxes.
I have referenced the UserControl at the top of my webform and also within each view.
<%#Register TagPrefix="uc1" TagName="userTimes" Src="~/usercontrols/userTimes.ascx"%>
<uc1:userTimes id="userAppointmentTimes" runat="server"></uc2:userTimes>
can’t seem to access the textboxes from the code behind. I need to firstly populate the textboxes and also hold any updated information to be re-inserted back into the database if changed.
Also each textbox has two Validation controls:
First makes sure it is in time
format HH:MM
Second makes sure the arrival is
before the seen time etc
My two questions are:
How do I access the UserControl from
the code behind? I have read that I
need to use the FindControl but I
don’t understand why, when I know
what it is called.
Do I undertake the validation
(server side) within the UserControl
code behind or the webform code
behind?
Thanks in advance for any help.
Clare
1.) You can access the User Control by its ID from the page's code behind - userAppointmentTimes in your case. To access your TextBoxes within the webform you need to use the FindControl-Method at the User Control level. So something like userAppointmentTimes.FindControl("WhateverTextBoxID") should work. You need to cast the result to TextBox of course.
You can't access the text boxes because ASP.Net does not automatically expose them for you. So alternatively you can provide public properties to set/get values to/from your textboxes inside your user control.
Within the user control, you can access your textboxes by their IDs.
2.) Put the validation controls inside your user control.
By webform you mean it's all inside the asp.net form-tag or do you have an asp.net form like FormView nested inside? If the latter is true you need to use FindControl at the FormView level - formView.FindControl("userAppointmentTimes"). Otherwise the user control is accessible from page level via its ID.

Categories

Resources