Programmatically created RadioButtonList needs 2 clicks - asp.net

I have a page (using MS Ajax). depending on other options, I may need to create a radio Button List inside a Panel.
This is done as per below.
RadioButtonList rbl = new RadioButtonList();
rbl.SelectedIndexChanged += new EventHandler(answer_Click);
rbl.AutoPostBack = true;
foreach (KeyValuePair<string, int> d in _answers)
{
ListItem li = new ListItem(d.Key.ToString(), d.Key.ToString());
li.Attributes.Add("class", "radio");
rbl.Items.Add(li);
}
p.Controls.Add(rbl);
this works fine, unless after the postback I need another RadioButton List. The list is drawn correctly, with all the correct options, but now when I click on an option the first time, it fills in and then resets. It takes a second click to get it to set and trigger the SelectedIndexChanged Event.
Im destroying and recreating the rbl once answer_Click is triggered (I know this as the next question that is created has different answers and options).
So, any ideas as to why it is I need to click twice on the second List?

Matt!
Looks like you have a ViewState issue. Controls are created after the LoadViewState trigger, so they doesn't get their values from the browser to load. You must save this value somewhere, using JS, ViewState, QueryString, Session, DB to persiste the state, and then load the selected value into each one.
Hopes this help you! Take a look here for more info about ASP.NET Page Life Cycle.

Related

checkbox not firing event after checked is set programmatically

I am iterating through a string of characters and finding a checkbox. I find the checkbox without any problems and if the character of the iteration is equal to 't', I set the Checked property of the checkbox to true.
However, for whatever reason, although it does check the appropriate checkboxes, executing this code also means that when I click any checkbox myself, nothing happens (everything works just fine and I can check anything until I execute this code). Also, the submit button on my page no longer does anything if I execute this code. I'm puzzled as to what may be the reason for this.
The buttons are created programmatically on init and are located inside an update panel.
DateTime date = new DateTime(2015, 11, 18);
foreach (char c in attendee.accommodation)
{
ID = "accommodationCheckBox" + date.ToShortDateString();
CheckBox checkbox = (CheckBox)FindControl(ID);
if (checkbox != null && c == 't')
{
checkbox.Checked = true;
}
date = date.AddDays(1);
}
Here is an example of how the checkbox looks like in the end: https://jsfiddle.net/Lzxo047o/
EDIT: Scenario: You fill in a dynamically generated form on A.aspx, then you see a "registration overview" on B.aspx. If you want to modify your registration at that point, you hit a button which creates a new instance of A.aspx and fills it with your registration data from database, which is what I'm solving right now. I dynamically create some checkboxes and based on a value of string, either check them or not. They get checked as they should, but I'm unable to manually control them / click them.
checkbox.CheckedChanged += yourcheck_event;
If the checkbox is created dynamically, you have to add the event to it.
Make sure your UpdatePanel has it's UpdateMode property set to "Always".
Take on count that:
the UpdatePanel control’s content is only updated when one of the
following is true:
When the postback is caused by a trigger for that UpdatePanel control.
When you explicitly call the UpdatePanel control's Update method. When
the UpdatePanel control is nested inside another UpdatePanel control
and the parent panel is updated.
…

Save the checked status of a CheckBox included inside an ASP ListView

I know there are similar questions about this issue (for example, here and here) but no one results helpful for my problem.
I have a ListView control showing all the users registered in the database and there is a CheckBox for each user shown if the user is approved or not, and I wanna save the changes directly when the CheckBox's Checked property changes.
I know it's not correct to add the event handler on the ListView_ItemDataBound, because after the CheckBox's AutoPostback there is not a new binding, thus the event handler get lost. On the other hand, I can't append the method directly on the ASPX file because this way I can't know which user is affected by the change (at least, I think I can't).
Any sugestion?
Thanks a lot
You have a couple of options.
It's possible that the ListView.ItemCommand event might fire. I'm not sure, though, because the documentation just specifies buttons. You might want to experiment.
The other option would be to harness the ListView.ItemCreated command. I believe that this always runs, regardless of whether the ListView is bound or not, because the item always has to be created, even if it's from ViewState. What you would do in the event handler for that event would be to attach an event handler to the CheckBox Click or CheckChanged event (I forget what the server-side name is for a CheckBox state change event).
So i ran into the same problem. i'm curious, on your page load are you checking if its a postback?
if(!Post.IsPostBack){
//normal page load
}
If you don't have that check, it will call your page load logic, in my case it was resetting the checkbox everytime with my data object.
On the aspx on the checkbox OnCheckedChanged="ckbNameOfCheckbox_CheckedChanged" AutoPostBack="true"
In the code behind
Protected Sub ckbNameOfCheckbox_CheckedChanged(sender As Object, e As EventArgs)
Dim chkBox As CheckBox = CType(sender, CheckBox)
' Gets the item that contains the CheckBox object.
Dim item As ListViewDataItem = CType(chkBox.Parent, ListViewDataItem)
NameOfTheListView.UpdateItem(item.DisplayIndex, sender.Checked)
End Sub

Grid View View state

I'm Using a GridView in my Application.
My GridView has a checkbox column and when the checkbox is clicked, the page is redirected to an other form.
When I return to previous from, nothing comes and GridView data is lost.
I used session and it's working fine, but I want that checkbox which was clicked to also maintain there state.
Is there better method to do this?
Upon redirection to the next page, Iterate your Gridview to update your Datatable with a checked checkbox column and then set that datatable to a session variable. I am assuming that you are already storing your source Datatable to a session.
Sorry, but no other magic work around !!!

online quiz using ASP dot NET

Hii,
I need to develop an online quiz website that would be having MCQs. I would want to have one question appearing per page with a Numeric Pager so that the user can go back and forth.
I tried using the FormView for displaying the questions and RadioButtons. I created a class QANS that would hold the answer selected by the user for the questions that he did answer so that I can later sum up the total Score.
Now, the problem I'm facing is as below:
Let the user select a RadioButton, say R, on a PageIndex, say I, and then go to some other page, say K. When the user returns back to page I, none of the RadioButtons is selected.
I tried adding code for setting the Checked property of the RadioButton true in the Page_Load(), but it didn't help. I also tried the same with the PageIndexChanged and PageIndexChanging event, but the RadioButton doesn't get checked.
The RadioButton that was selected for a particular question has been stored and I am able to print which one it was using Response.Write() but I'm not able to keep the RadioButton Checked.
How shall this be done?
You should be able to make the radio button checked in the
protected override void OnPreRender(EventArgs e)
event of the page lifecycle
Have you considered using the .Net wizard control for this?
The ASP.Net 2.0 Wizard Control
You can save the state of the selected controls in session and repopulate them after the round trip.
It's odd that it's losing state after the postback. Is there any crazy code in you on_load or pageIndexChanging or anything?
From what I understand, you have to persist the checked state of the radiobutton across the pageindexes. You can use ViewState for that as that can preserve data across postbacks for a page.
something like this:-
// Define a list of question ids attempted
List questionIdsAttempted;
//Add the List to the ViewState
if(ViewState["QuestionIdsAttempted"]!=null)
{
questionIdsAttempted= new List()
ViewState["QuestionIdsAttempted"] = questionIdsAttempted
}
// Add the question id to the list when when the user attempts a question
questionIdsAttempted.Add(qId);
// Add the list back to the viewstate
ViewState["QuestionIdsAttempted"] = questionIdsAttempted
And in the page load in checked attribute of the radiobuttons , you can call a function with the current question id and the function will get the list from the viewstate and returns true or false based on if the id exists in the list.
Ofcourse, you need to check the nullability of the viewstate in various places based on the flow of the program.
Let me know

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