Spent quite a lot of time today getting to grips with dynamically placing user controls on a page at run time. I wanted a series of buttons which were determined by database entries and these buttons needed to have code to display a page when clicked. If your wondering how to do this yourself you need to know about Page.LoadControl and AddHandler;
- Create a sub for the click handler with the usual ByVal sender As System.Object, ByVal e As System.EventArgs parameters.
- Use controlvariable = Page.LoadControl to load an ascx into a variable (defined to be the type of the user control)
- Assign the controlvariable.id to something useful
- Do a me.controls.add controlvariable to add it to the page (or a me.container.controls.add if you've got your page divided up into tables or the like)
- Do an AddHandler ctype(me.controls(controlindex), control type).Clicked, AddressOf nameofclickhandler
The click handlers sender property will have the control (as type object so you have to cast it again) so you can inspect the ID and find out which button was clicked and act accordingly. For my example I made a custom control which had a few basic properties of a button object exposed plus an additional one for the page name associated with the button. That way it was instantly available from the object passed into the click event handler and i could do a response.redirect with it.
A lot of work casting back and forth for a newbie to this but it works, would recommend putting these controls into a table/div/whatever block so you can keep track of the control indexes, also found it useful to make a quick hash table to store the control objects and their ID's for easy access to each control.