Change the Sort order for ContentByQueryWebPart (CQWP)

In a custom version of the ContentByQueryWebPart, the items that were displayed from a list were not being sorted in any meaningful way.  The default sort is the created date.  To fix this, there are a few properties that needed to be added in the implementation using the object model approach.  The properties are “SortBy”, “SortDirection”, and “SortByFieldType.”  Here is how this is done in code and note that the “SortBy” field is not the title of the field name but the item ID:

public class CoolNav : ContentByQueryWebPart
    {
            static string listGuid = String.Empty;
            static string url = String.Empty;
            static string itemStyle = "LinkList";
            static SPList list; 

            public CoolNav() : base()
            {
                if (listGuid == String.Empty)
                {
                    listGuid = SPContext.Current.Site.RootWeb.Lists["Cool Navigation"].ID.ToString();
                    list = SPContext.Current.Site.RootWeb.Lists["Cool Navigation"];
                }

                if (url == String.Empty)
                {
                    url = SPContext.Current.Site.ServerRelativeUrl;
                }
            }
            protected override void OnLoad(EventArgs e)
            {
                base.OnLoad(e);
                this.ListGuid = listGuid;
                this.WebUrl = url;
                // Sort Properties
                this.SortBy = list.Fields["Order"].Id.ToString();
                this.SortByDirection = SortDirection.Asc;
                this.SortByFieldType = "Number";
                String ServerURL = SPContext.Current.Site.ServerRelativeUrl;
                //Fix the URL Path
                if (!ServerURL.EndsWith(@"/"))
                    ServerURL += @"/";
                this.MainXslLink = ServerURL + @"Style Library/XSL Style Sheets/CoolNav.xsl";
                this.ItemXslLink = ServerURL + @"Style Library/XSL Style Sheets/CoolNav_ItemStyle.xsl";
                this.ItemStyle = itemStyle;
                this.CommonViewFields = "URL,text";
            }
     }
  1. Leave a comment

Leave a Reply

Please log in using one of these methods to post your comment:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

%d bloggers like this: