1

I am fairly new to SharePoint development but I come from a ASP.NET background. I am trying to get a clear explanation of the rationale for creating the UI controls in CreateChildControls vs creating them using declarative style in the .ascx file.

I have found several blog posts and articles that say that you should always use CreateChildControls but they do not explain why. I have several web parts that I have created using the declarative style that seem to work fine. I am worried that because of my inexperience with SharePoint I am unaware of best practices or limitations that I will run into by developing this way.

4

Don't worry. The pure use of CreateChildControls is only due to old habits of SharePoint developers due to the way Web Parts was developed in the past.

If you prefer to build your web parts declaratively due to the increased productivity then just use that method.

The only reason to prefer CreateChildControls is if you need the extra flexibility of adding child controls dynamically.

Here is some of the history of web parts to explain where a lot of SharePoint developers got their habits from.

SharePoint 2003
This was the first version of SharePoint build on top of ASP.NET, but it used it's own page parser so .ascx files wasn't supported which meant that the use of CreateChildControls was the only possibility.

Later versions of SharePoint
These are "pure" ASP.NET applications which fully support .ascx files.
But the method of creating web parts was limited by the support of different Visual Studio versions

Visual Studio 2008
No built in support for Visual Web Parts so most developers continued to use CreateChildControls as this was what they got out of the box.

Visual Studio 2010
Introduced Visual Web Parts, but what it created was a web part which was a thin wrapper around a UserControl which it loaded using Page.LoadControl which loaded the .ascx from the file system. This had two drawbacks:

  1. Could not be used in Sandboxed solutions (but do we really care?)
  2. It was cumbersome to use Web Part properties and connections as these had to be implemented in the web part and then somehow delegated forward to the UserControl which had the main logic

The last part meant that most SharePoint developers continued to use CreateChildControls

Visual Studio 2010 SharePoint Power Tools, Visual Studio 2012 and later
Introduced a new paradigm for the Visual Web Part (depending on the version it either has Sandboxed or lacks Farm Solution Only in the name) , where Visual Studio generates a partial class based on the .ascx file which is "merged" with your class, this generate a pure web part which is functional no different than the one created using CreateChildControls.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.