I开发者_高级运维 have a checkboxlist and textbox controls on my asp.net page and the are dynamically created and added to the page. When I populate the values and submit the form, the values are empty by the time it hits the server. Any help?
They are empty because they are being re-created too late in the page lifecycle.
Without knowing the precise point in the ASP.NET Page Lifecycle you're adding your controls, (though I'd guess it's either Page_Load or an event handler), it goes something like this:
- Build control tree
- Add dynamic controls
- Render
(Postback)
- Build control tree
- Reconstitute viewstate & bind to Post values
- Add dynamic controls
- Render
To solve this, you need to make sure your controls are created early enough in the lifecycle. Standard practice is to break the "control creation" into a separate method, and during CreateChildControls, check to see if they need to be created:
override CreateChildControls()
{
if(IsPostBack)
{
EnsureDynamicControlsAreAdded();
}
}
This way, if they do need to be initially added by something as far late in the lifecycle as an event handler (Button_Click, for example), you can call the same EnsureDynamicControlsAreAdded
method from there as well, and on the next round-trip they'll be created much earlier.
Further to Rex M's answer, you could try creating the controls in the "Page_Init
" event - this is one of the first events in the page lifecycle, and is where I would normally create controls in a viewstateless page (NB: If you do this, do not surround the content of the Page_Init handler with an "if (!IsPostback)
" - this will prevent it from working as intended).
精彩评论