简体   繁体   中英

C# dynamically generated controls in Page_Load or PreRender?

I have ac# web application where I need to dynamically generate controls, and where the actions on the controls also affect which controls will be rendered. Imagine for example a list of buttons, where each button should remove itself (and its reference in the database). I have the feeling I don't understand something quite basic here (at least it should be)

I would like to use event handlers here. However, the question is then where should I generate the controls, in Page_Load or PreRender? If I generate them in page_load the event handlers haven't fired yet so the generated content isnt up to date yet. I can also generate it in PreRender but then the event handlers don't fire because the controls dont exist yet.

What would be the preferred way of handling this? I really want to avoid the option to modify the generated content later, it is way too error-prone in my case. I would like to generate all content from scratch, right after the events have been handled. Currently I solve this partially by examining the request.form before the generation of the controls but I have quite a lot of actions and it's not really a workable solution in quite some cases already.

I create controls by overriding OnInit

That means they are available for the viewstate to restore any values to them, OnLoad is too late for this.

PreRender is for last minute things like populating textboxes and rendering scripts

Note however your controls must rebuild after a postback in exactly the same way for the values to be restored (same IDs etc).

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM