Location Aware Content Query Web Part for use in Page Layouts
The Content Query Web Part (CQWP) is a useful tool for displaying data within a site. If you want to use the CQWP in a Page Layout to rollup information relative to the current location you have to perform some manual configuration. After creating the page, you would have to tell the CQWP where to get its data from. Wouldn’t it be nice though to create the page using the desired page layout with a CQWP already added and it automatically knew the location in the site hierarchy. This may be easier than you think.
To accomplish this you would create what I call the Location Aware Content Query Web Part. Basically, create a new Web Part that inherits from the Microsoft.SharePoint.Publishing.WebControls.ContentByQueryWebPart, then, override the CreateChildControls method and add two lines of code.
First, create a new Visual Studio project using the SharePoint Web Part project template.
Add a reference to Microsoft.SharePoint.Publishing.dll to the project.
Now, let’s add our code.
Notice that by default, the SharePoint Web Part template uses the Render method. I removed this from the file and replaced it with an overridden RenderWebPart method that in turn calls the RenderWebPart method of the base class. The main addition in functionality is done by overriding the CreateChildControls method. In this method we use the SPContext class to determine the current site within the hierarchy and pass the AbsolutePath property of the Uri class to the WebUrl property of the web part.
We now have a new Content Query Web Part that is aware of its location within the site hierarchy. We can now include this as part of a page layout. When a page is created from the page layout, the web part would automatically be aware of its location and display the desired content using the style specified in the page layout.