I want to create control that will allow user to design his own website structure. I imagined that inside UpdatePanel is control(s) with TextBox ( for page name) and Button ‘add below’. It would looks like:
| "Questions" |
| [ add below ] |
| "Tags" |
| [ add below ] |
| "Badges" |
| [ add below ] |
now when user click on button in “Tags” element there should appear new one, between “Tags” and “Badges”, with editable name, so user can name it “Users” for example. It should be done without full postback ( to avoid page blinks).
Now is my problem: I cannot load those controls (at last not all of them) in onInit since they dont exist, but I have to attend to theirs click event so I should attaching event listener what should be done during Init phase. How can I achieve described functionality?
I played around it for too much time and I am confused. I would be grateful for any tips.
This is a tricky situation because you are dealing with dynamic controls you need to populate them on page init in order to persist viewstate, also events for controls added inside an update panel during button clicks do not seems to get registered until the next postback, so the normal button click event only fires once every other time you click on a newly added control. There may be some other way to work around this than the way I did it. If anyone knows I would like find out.
My solution is to keep a list of what you have added dynamically, and store it in a session variable (because the viewstate is not loaded during page init). Then on the page init load any controls you have previously added. Then handle the click event during the page load with some custom code instead or the normal click event.
I have created a sample page to help test this.
Here is the code for the aspx page (default.aspx):
And here is the code for the code behind page (default.aspx.cs):
Let me know if this code helps you out at all. I tried to add comments with my understanding of what is going on and how it works.