1

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.

How is should be

How it really is

John Saunders
  • 160,644
  • 26
  • 247
  • 397
Alen
  • 145
  • 1
  • 1
  • 10

2 Answers2

1

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.

BBQ
  • 618
  • 1
  • 7
  • 20
  • I dont really know where the problem lies, so i thought it unpractical to post ALL my code from both my aspx.cs and my ascx pages :P Do you mean i should put this in the Page_Load event of the ASCX page or the page_load of the ASPX.CS page? cuz on my aspx.cs page i have this, but on the ascx page the page load event is empty... – Alen Jan 23 '13 at 14:41
  • just the page load event of the aspx.cs and the event handler for the button in the aspx.cs will do I think ;) – BBQ Jan 23 '13 at 14:43
1

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.

Destrictor
  • 752
  • 1
  • 4
  • 15