Reputation: 523
I have a problem that I cant seem to find a solution to, even though there are very similar questions to it.
Basically I have text boxes that are programmatically created in my Page_Load method. They are filled with values from certain cookies.
I then have a 'Update' button, which, when clicked, should update the cookie that was loaded into the textbox.
So I gave the ID of the text box, the same name as the cookie, then on the On_Click method of the update button, I cycle through the text boxes and update the cookie (ID name) with the value in the text box.
However, this is not working. What I have tried is as follows.
The controls are simply created in the onload method. Then when you click the button after you have changed the text box, the onload method is called again, thus changing the textbox back to the original and updating it the way it was.
The controls are created in the onload method after checking for if (!Page.IsPostBack)
. This does not work because the page load method is called first and doesn't create the controls on the screen. Your left with a blank screen and no updated cookies.
I tried EnableViewState
which didnt work, and I tried creating the controls on their own when (Page.IsPostBack)
but still nothing.
Any ideas?
Upvotes: 1
Views: 782
Reputation: 781
You should create the controls during the Init event and you need to do so on every load (dont check IsPostBack). In order for these controls to raise postbacks and have their properties set from the viewstate they need to be in the page hiearchy before the events are fired.
If you are just creating the controls during Init and then only setting the data in the Load event after checking IsPostBack, then they will retain the text entered on the website since they will first be initialized and then populated from viewstate data.
Upvotes: 1
Reputation: 2583
Yuo should create the controls in the onLoad method and give them the initial value inside the if (!Page.IsPostBack)
code block. This way you will create the control tree everytime but you won't reinitialize the values loosing the updated values.
Upvotes: 3