Dynamically Created User Control's Dropbox Items from Database resets on postback - c#

First off, I have managed to create a web application where my dynamically created user controls are recreated and repopulated with the correct information upon postback. I am not sure what my problem is, but i hope that you will be able to help me figure it out based on my situation:
On my page i enter the number of controls to be created into a hardcoded textbox (its on the aspx page) and click the okay butten. This in turn, creates the specified number of user controls dynamically using c# in the background.
So far the desired number of dynamic controls are in a table on the page.
Next...
I have 1 textbox and 4 dropboxes on each dynamic user control. When i type a company name into the textbox field and press enter or click away (on text changed event) it autoposts back and the textbox retains the company name that i have typed in.
Based on this string the dropboxes are populated from the database. Now when i select the desired items from the dropboxes and click on the save button (located outside of the dynamic controls, on the page) it does an insert to the database, but it turns out that upon this postback the indexes from the dropboxes have been reset and the wrong values get inserted.
The following pictures show firstly, how it should be and then how it is.
Basically the company name remains in the textbox of the dynamic control, but the information i choose from the dropbox resets to the first index.

It's hard to tell what happend without code, but this is a common mistake:
If you fill/create the dropdownlist controls in the page load event and you post back, the code will refill/recreate the controls. That's why you have to use something like If(!IsPostBack) in your page load event. Otherwise it will execute that code everytime you do a postback and actually just want to execute the code in your event handler for that button.

If you're dynamically creating the controls, make sure to do that in the Page_Init event. Dynamic controls have to be recreated on every postback. Their state is restored after the Page_Init (if it is a postback), so make sure to only set their values in Page_Load if you want to overwrite them.

Related

How to set up page loading in ASP.Net for dynamic gridviews?

Here is how my code is set up.
The webpage itself works like this:
You have a drop down that allows you to select between different values. Lets call it dropdown A. Depending on the value selected, a gridview gets generated.
How generation works:
When a item in the dropdown A gets selected, inside the selectedIndexChanged is a method call to a function that creates a DataTable. That datatable gets binded to the gridview inside selectIndexChanged.
When it gets bounded, onRowBoundEvent gets called, and this is where I add all the necessary controls with unique IDs.
There is a button called saved that looks at the data in gridview, and saves it.
Problem: When I press save, there are no controls in the gridview for me to find.
I can use findControl since I know all the ids, but how do I make the controls stick around?
If I bind it in the page_load, how do I know what gridview to generate since if I select a value from dropdown A, page_load still fires before I can get a selection value from dropdown A, so I can't make a simple conditional statement based on the dropdown value.
I can't show any code, sorry. But this is more of a conceptual question I have.
I was able to figure this out on my own.
PrePage_Load during the project lifecycle has access to controls. Dropdown A in my example can be accessed in PrePage_Load, allowing me to get the necessary values and set them before Page_Load starts.
For controls in the gridview, I made it so the gridview does not automatically load from viewstate, and I rebuilt the gridview myself during page_load.

How to append controls to a panel?

I am developing a dynamic website in ASP.NET. As a trial I tried a code shown below, that adds some controls to Panel1. When user clicks a button for the first time the controls are added to the Panel but when user clicks the same button for second time, the previous controls are replaced with new ones. But I want the controls to be appended one after the other each time the user clicks the button. The code is something like this:
Control c=Page.LoadControl("DData.ascx");
Panel1.Controls.Add(c);
I also tried
Control c=Page.LoadControl("DData.ascx");
Panel1.Controls.AddAt(Panel1.Controls.Count,c);
But this replaces the first output. Please tell me how to append these controls?
As you would expect, this appends a single control:
Control c = Page.LoadControl("DData.ascx");
Panel1.Controls.Add(c);
You can append as many controls as you wish in this fashion.
However, you need to keep track of the controls you are adding in some persisted/stateful fashion (database, Session, ViewState, etc.).
You need to rebuild the control tree every time the page loads.
See my answers to similar questions:
https://stackoverflow.com/a/10050755/453277
https://stackoverflow.com/a/9545079/453277
It may be about the life cycle of asp.net page. Each time when page loads it returns to the initial state. Button Click events are handled after page load and you have only one control at the page. Please look Button to dynamically add controls everytime it's clicked

how do I save custom user control viewstate during postback?

I have written the user control InputDetails that has a few text boxes and a few radio boxes inside it.
I add it dynamically during Page_Load:
if(!Page.IsPostBack()){
InputDetails input = (InputDetails)Page.LoadControl("InputDetails.ascx");
PlaceHolder1.Controls.Add(input);
}
but when I refresh the page, the control is gone, so I'm asking, how do I save the user control in the viewstate that it has been added, so it automatically reloads it next time. Better yet, how do I read the values put in the text boxes of the user control when the page is posted back? I need to be able to add multiple InputDetails on a single page so saving it would be useful.
If you add a control to the page dynamically, you have to recreate it after each postback.
Try to remove the if (Page.IsPostBack()) line and check if it works :).
For each control you create, you should also set the same ID value each time it's created.
If there are no other issues, the ViewState should then be able to save state of the controls across postbacks.
In order to read the values, you can:
add some public properties to your user control in order to get access to the values you need
or
use TextBox txtBox = (TextBox)myCustomControlObject.FindControl("nestedTextBox") method to find (more information here: http://msdn.microsoft.com/en-us/library/486wc64h.aspx)
You can load user controls / server control dynamically using AJAX also and viewstate requires controls ID to store the viewstate properly.
would you pls go through this link for more info

Wrong state in Server Controls with same ID's when dynamically adding UserControl to UpdatePanel

Here is what I am trying to do. I have a page with two link buttons and an updatepanel (the two linkbuttons trigger the updatepanel). I have two usercontrols which have labels with same ID's. When I click the first link button, I add the first usercontrol to the updatepanel and set the label value to datetime.now
when i click the second link button i add the second usercontrol but i see that the value of the label from the first control is set in the label in second user control. if the id's are different there is no problem - but in my case the usercontrols are being developed by different teams and I am integrating them in the way i mentioned - so they may have same ids.
i have browsed all over and tried various suggestions but i cannot get this to work, any help will be greatly appreciated.
Thanks
Job Samuel
Your problem has nothing to do with the UpdatePanel, actually.
Imagine what would happen if you had a 3rd LinkButton, which did nothing but postback. What would happen if you clicked the 1st LinkButton, the UserControl appeared, and then you clicked the 3rd one? What do you expect to see? If you think you will see the UserControl again, you are wrong. Dynamically created controls must be created every request, they don't stick around automatically. ViewState remembers the state of controls on the page, NOT what the controls themselves are in the first place -- thats what the markup in the aspx page does. Dynamically created controls obviously arent in the markup, so they arent automatically recreated.
You need to think of the lifecycle of a control as 'straddling' half way between two requests. It starts half way into one request and ends half way into the next. You need to save which user control is currently displayed in either a hidden field or a Page.ViewState value (not the user control itself mind you, just whatever information you need to figure it out), then reload that control from the page's OnLoad. If you do that -- the sequence will go like this:
(1) Click LinkButton1
(2) UserControl1 dynamically created
(3) Click LinkButton2
(4) Page.OnLoad reloads UserControl1
(5) UserControl1 loads its postback data and viewstate
(6) LinkButton2's click event fires
(7) Remove existing UserControl1 and add UserControl2 dynamically
(8) UserControl2 can have the same ID, since UserControl1 already 'consumed' its state.
I suggest you browse my series of articles on Understanding Dynamic Controls in ASP.NET:
http://weblogs.asp.net/infinitiesloop/
You have to set a different id for the label when you create the user control.

How to save user entered data to session state from a dynamically created control?

using c# (asp.net)
i'm programmatically creating several drop down lists (random number).
the user selects a particular value from each list and i need to save the user selected value.
if i try to save the data to session state by using a button click event it says the drop down list object hasn't been created. (obviously cuz i'm creating the drop down lists in the page load event under !IsPostBack.)
if i try to save the data to session state in the page load event under IsPostBack i only get the first value from each list. (obviously cuz when the page is recreated after the postback, the drop down lists have been recreated and the user entered data is lost).
How do i save the user selected value from the drop down lists when a button is clicked?
i'm doing this in the code behind file.
As John Saunders said, you have to recreate all of your DropDownList controls on every postback. Additionally, you have to create them before state is restored. That means that "under !IsPostBack" in the page load event is already too late. Move it up to Page Init.
You have to recreate all of the dropdowns on every postback.
Personally (without the ability to switch to MVC) I would consider getting rid of the postbacks altogether and reading the values back directly from a standard HTTP POST request.
The implementation of dynamic controls with postbacks often ends up rather convoluted and difficult to follow

Categories

Resources