I create some tables dynamically in C#, and they are giving me viewstate issues. I have a checkbox table and a number entry table that depends on the first. When I press a button that causes postback, I get some problems. Here is a flow chart.
Page_Load
- create checkbox table
- create number entry table (check box is always empty, table has wrong number of rows, but numbers are populated correctly from postback)
Postback button
- create number entry table (check box is now populated, table has correct number of rows, but numbers did not survive postback).
Is there a way I can load the viewstate to the checkbox table before I create the number entry table? I have tried to create the number entry tables in one or the other place (on page load or postback button method), but neither is completely correct. I know that dynamic content needs to be created on every load for the viewstate to appear.
I suspect I may need to create a datatable and store that in the viewstate for the checkboxes to reappear correctly…
I would add your dynamic controls in the
PreInitorInitevent of your page. Although you can add them afterwards, after theInitphase is whenViewStatedata is loaded for controls.If you add your controls during the
Page_Loadthe control has to play catch up, which means it runs through all of the events in the page lifecycle until it catches up with the rest of the page. This might be causing the issue you’re seeing.Here’s an excellent write-up regarding the
Page LifecycleandViewState:http://www.codeproject.com/Articles/24611/ASP-NET-Internals-Viewstate-and-Page-Life-Cycle