Wednesday, 11 December 2013

How to add buttons dynamically to ASP.Net

If you don't know how many of something you need on a page, ASP.Net allows you to add controls dynamically. These dynamically loaded controls are unfortunately forgotten each time the page is posted back and needs to be reloaded at every postback as well as the first time the page is requested. To be able to access their values through the viewstate you are best adding them as early as possible (Page_Init) and populate them and customize them in the Page_Load event. To read an excellent article about this please visit the 4guysfromrolla website which goes into this in great detail.

However, what if it isn't just a value you want to access but instead want to access an event from a dynamically added control such as a button? Events are only raised after the Page_Load has taken place and then your controls have already been regenerated.

The way to solve this as I have found (if there is a better way let me know!) is to specifically reload the section that should be updated by the button click after first having cleared it of the controls that the postback generated in the Page_Init stage if  there are controls already there that you wish to update. Failure to clear the placeholder means that  they would be added twice (one with the old values as the button event hasn't been raised yet and once with the new values) which isn't allowed unless your IDs are different. Please see example below which tries to demonstrate this.



No comments:

Post a Comment