I am creating ContentQuery Webpart programatically, To improve the performance i am following the below post(http://blogs.msdn.com/b/mimorr/archive/2009/11/19/improve-performance-of-content-query-web-parts-using-viewfieldsoverride.aspx). I would like to know, how to use ViewFieldsOverride property in CQWP programatically.
1 Answer
How to set ContentByQueryWebPart.ViewFieldsOverride property programatically (example):
cbq.ViewFieldsOverride = "<FieldRef ID=\"{fa564e0f-0c70-4ab9-b863-0177e6ddd247}\" Nullable=\"True\" Type=\"Text\" /><FieldRef ID=\"{94f89715-e097-4e8b-ba79-ea02aa8b7adb}\" Nullable=\"True\" Type=\"Lookup\" /><ProjectProperty Name=\"Title\" />";
Example:
public static void AddDiscussionAggregatorWebPart(SPWeb web, string pageUrl, string zoneId, int zoneIndex)
{
using (var cbq = new ContentByQueryWebPart())
{
cbq.Title = "Latest Discussions";
cbq.SortByDirection = ContentByQueryWebPart.SortDirection.Desc;
cbq.ContentTypeBeginsWithId = "0x012002"; //Discussion Content Type
cbq.SortBy = "{28cf69c5-fa48-462a-b5cd-27b6f9d2bd5f}";
cbq.WebUrl = "~sitecollection";
cbq.ServerTemplate = "108"; //Discussion Board List Type
cbq.ViewFieldsOverride = "<FieldRef ID=\"{fa564e0f-0c70-4ab9-b863-0177e6ddd247}\" Nullable=\"True\" Type=\"Text\" /><FieldRef ID=\"{94f89715-e097-4e8b-ba79-ea02aa8b7adb}\" Nullable=\"True\" Type=\"Lookup\" /><ProjectProperty Name=\"Title\" />";
AddWebPartOnPage(web, pageUrl, zoneId, zoneIndex, cbq);
}
}
public static void AddWebPartOnPage(SPWeb web, string pageUrl, string zoneId, int zoneIndex, WebPart webPart)
{
var page = web.GetFile(pageUrl);
using (var wpm = page.GetLimitedWebPartManager(PersonalizationScope.Shared))
{
try
{
wpm.AddWebPart(webPart, zoneId, zoneIndex);
wpm.SaveChanges(webPart);
}
finally
{
wpm.Web.Dispose();
}
}
}