Control Injection for SharePoint Web Parts
This week has been pretty busy so I haven't even got to my blog backlog as well it was a bit of a living hell for me as we were experiencing various problems with a few common components that provide mail which in turn required us to do a quick "comment out" code release to demo a product. Anyways, now that that's over and it's July 1st (Canada Day, much like Independance Day that Americans will celebrate on the 4th but without the aliens).
I was on one of my more favorite geek sites, The Code Project, and found an interesting article that resonated with the SharePoint side of my brain. The author wasn't too happy with the lack of design support for building ASP.NET server controls (as are all of us that write Web Parts) and came up with an interesting solution to the problem. He uses an approach similar to string.Format to inject controls into a composite control layout string. After a couple of iterations he then took the HTML page for his composite control and made it an embedded resource in his server control and this became the layout string to inject the controls into.
The same principle can be easily applied to Web Parts. Just create a new embedded resource which is your HTML layout then in your CreateChildControls call, create the controls and inject them using the layout file. It still has it's drawbacks so something like SmartPart and User Controls give you the design-time capabilities that this doesn't offer, but it's a good alternative if you're struggling writing out gobs of HTML in your codebase and doesn't require deployment of .ascx pages or anything. Check out the Code Project article here.