Changing Dynamic Controls via DropDownList on Content Page - asp.net

Problem: Content Page with Wizard Control with UpdatePanel and Placeholder. Above the UpdatePanel is a DropDownList. I need to display different input controls below the drop-down list when the user changes the selection in the drop-down list. When the user clicks 'Next' on the wizard control, I need to be able to get the data out of those dynamic controls as well.
I know all the dynamic controls have to be created in the OnInit method in order to get the data back from those controls during the postback. However, when the drop-down list's SelectedIndexChanged event is fired, the OnInit method is called... then the PageLoad... and finally the handler for the SelectedIndexChanged event is called. ViewState hasn't been restored until well after the OnInit & PageLoad methods have been called, so there is no way to know what the user chose in the list box at the time OnInit is called... which exactly when I'm required to create the dynamic controls.
So... how do you solve this problem? Do you just have to write the entire page, or most of it, using JavaScript?
Thanks in advance.

I tend to use an old school method for this type of requirement. I would write all of the controls that are needed in the update panel, with their Visible property set to false. Then, on post back read the drop down's state and set the approperate controls Visible property to true. This way there is no "dynamic" controls, and due to the fact that controls whose Visible property is false are not rendered, they are not downloaded until the user should see them.

you can also use an asp:hiddenfield and set the value to a case var you mentally create. then run a small jQuery script on top to look at
$(document).on("change", "#ddlSelector", setControls);
then just make a function, for instance:
function setControls(event) {
event.preventDefault();
var selector = hiddenfield.val();
}
then any item to show/hide can be done with getting the tag:
$("#elementName").css("display", "inline");
or display, none to hide.
I used this at work because at times you need to change without firing the postback, but still collect data when they engage the form.
I typically avoid jQuery for many events for strength of code and security, but DOM element manipulation can be much easier at times with jQuery.

Related

Call Dynamic Control's Event if exists

The scenario:
I have some JSON data which I'm using to load stored-data into fields on my form. One of these fields is a DropDownList. The DropDownList happens to be in a child, of a child ASCX control, which I'm accessing from a parent ASPX page. When this DropDownList has its SelectedIndexChanged, it makes other fields visible on the form.
I'm using one of my functions to find this control, which is working successfully, but when setting the SelectedValue of my DropDownList control, the SelectedIndexChanged event is not firing. Meaning some fields aren't loading, resulting in some JSON data not being loaded and lost.
I have seen a suggestion of simply calling ddl_SelectedIndexChange(sender, args) function, but the page I'm calling dynamically loads hundreds of child controls depending on the current request, so was wondering if there is a way of invoking the SelectedIndexChanged event (if it exists) for a control, without having to search and manually call the ddl_SelectedIndexChanged() function. Is it possible?
DirectCast(WebUtils.ControlFinder(upMain, f.fieldClientID), DropDownList).SelectedValue = f.fieldData.ToUpper()
I hope it makes sense. Sorry if I haven't made this clear enough.
I ended up using Reflection to Invoke the properties event that I required, worked a treat.

Textbox autopostbacks

I have a custom asp.net user control which has an update panel in it. In this update panel i have all the controls and content that are shown to the user. Amongst these controls there are two textboxes, which have AutoPostback = true. This is because when their value is changed, the structure of the page changes accordingly. This works as required, but when I modify the two textboxes in quick succession, the first autopostback works while the second one doesn't fire. It seems that while it is doing the first postback, any other attempted postbacks will be ignored. How can I work around this?
This behavior is by design. The usual approach is to use UpdateProgress control that disables the user input on the page while the postback is in process.
Alternatively you could add your own onchange event handlers that call __doPostBack() more intelligently (by using timers etc.) to avoid this problem for your specific scenario. You could also try aborting any postback is process before submitting a new one.
A resource that might be useful: http://www.dotnetcurry.com/ShowArticle.aspx?ID=176

ASP.net PreInit() Vs Init()

From local forum i understood that PreInit can be used to handle the following
PreInit()
>Master pages can be called dynamically
>Themes can be set dynamically
>Programatically add controls to controls collection
and i read Init() is for
Init()
In this event, we can read the controls properties (set at design time). We cannot read control values changed by the user because that changed value will get loaded after LoadPostData() event fires.
Question
I am not getting the point "We cannot read control values changed by the user".Where do
users change the value of control?.Example would help me to understand the point.
PreInit: Raised after the start stage is complete and before the initialization stage begins.
Use this event for the following:
Check the IsPostBack property to determine whether this is the first time the page is being processed. The IsCallback and IsCrossPagePostBack properties have also been set at this time.
Create or re-create dynamic controls.
Set a master page dynamically.
Set the Theme property dynamically.
Read or set profile property values.
Init: Raised after all controls have been initialized and any skin settings have been applied. The Init event of individual controls occurs before the Init event of the page.
Lets say you have a textbox, a dropdownlist, some check boxes... the user enters data into them and you want to read their values by writing
var text = myTextBox.Text;
var selectedItem = ddl.SelectedItem;
this you cannot do before after the LoadPostData method has been called.
This page gives a pretty good summary of the different events and what they should be used for http://msdn.microsoft.com/en-us/library/ms178472.aspx. It says that PreInit should be used for ie. creating dynamic controls and Init for setting properties on them.
On the first post, you show several controls, say a textbox and a submit button.
The user types code into the textbox and click submit.
The user has changed the value of the control when he typed it in the textbox and it then got posted back to the page.
You will not be able to access the value typed in until LoadPostData has processed.
This is the pretty much the same with all other server side controls.
PreInit:
Initialize master page , user controls , dynamic controls
Init :
set the properties of controls
The value is changed through PostBack. The changes in the form data is determined by the current ViewState (which isn't loaded until later) vs the form data. Seeing as that isn't loaded until later, then you can't read any control values at that point.

button events in datalists

I have a datalist and want to dynamically add buttons to it. I am using the OnItemCommand datalist event and setting the CommandName/ CommandArgument attributes of the button.
However I am having trouble with handling the button click - does not seem to fire.
It works when I declared a button on the aspx page, but not for buttons that are dynamically created.
I hope this makes sense, and any help would be great.
Thanks
You can only create dynamic controls on PreInit or Init if you want to handle associated events. Otherwise, on postback, they won't exist at the moment of event handling and because of that, your handler method won't be called.
Internet is full of resources about how to handle dynamic controls. Let me know if you need any reference.

Dynamically Change User Control in ASP.Net

I'm trying to create a web page that will display an appropriate user control based on the selected value of a drop down list.
Basically the page layout is this:
Drop Down Selection
< User Control created based on drop down selection >
I have it half working... the controls are changing when the selection changes.
In OnInit(), I dynamically create the last selected control (whose value gets saved in session state because ViewState isn't available at OnInit).
When the drop down selection change occurs, I remove the old user control, and add a new one. The problem is: with the new control being added from the selection changed event, I'm not able to save changes from the user on the first postback. After the first post back, the selected control is created from OnInit instead of the Change event, and state is saved from then on, until the next selection change.
Here is the SelectionChanged method:
protected void SelectionChanged(object sender, EventArgs e)
{
SelectedValue = int.Parse(DropDownList.SelectedValue); //Store in Session
Control userControl = GetSpecificUserControl(SelectedValue);
PlaceHolder1.Controls.Clear(); // Remove old user control
PlaceHolder1.Controls.Add(userControl);
}
Any changes made to the new control by the user after SelectionChanged happens are not saved on the following post back. However, subsequent postbacks do get saved. At that point, the control is getting created in OnInit().
Is there some way to force the correct post back and ViewState when the control changes? Is it possible to force a page reinitialization after the control is changed?
What you need to do is keep the last known value of the DropDownList in the Session. Then:
OnInit:
Create whatever control is indicated by the saved value in the session
SelectionChanged Event
Remove whatever you created during OnInit
Create and add new control based on new DropDownList selection
Save new DropDownList selection in session
This way, on the next postback after a change you are re-creating the control that ViewState expected to find, and so it's state will be restored.
Dynamic controls can be very finicky. Often it is easier to create all of the controls you might possible need and set their Visible properties to false. This way they don't render to the browser at all. Then set Visible to true for just the controls you need when you need them.
This is the classic tear-your-hair-out problem with ASP.Net webforms. You have several options:
1) This is a bit of a hack, since it goes outside the intended page lifecycle a bit, but in my experience it's the most direct way of dealing with the problem. When the page posts back from the drop down selection event, simply poll Request["MyDropDownID"] for the selected value of the drop down control during Init() - don't wait for the OnMyDropDownChanged() event to set up your page.
2) Implement your own ViewState handling for your user controls. This requires digging into the ViewState documentation and overriding a number of methods.
3) Joel's solution. He beat me to it but I was trying to get first post :p
Other options involve posting values using javascript and such, but those get really messy.
If the list of options is not too big, you could just render all the user controls statically and use JavaScript/jQuery to show/hide the appropriate controls based on the value of the dropdown (onchange js event). You can use the dropdown value to extract the appropriate values from the user controls when saving.
You avoid the pain of dealing with dynamic controls, provide a more responsive UI when selecting from the dropdown (no postback), etc...
Don't add the control in the SelectedIndexChanged handler, add it during Page_Load. You'll just have to test the value of the dropdown each time the page loads, and load the correct control for that value.

Resources