I am programmatically adding a list on the site page.

The list is being added however the query that I am using for the view has no effect, Please find below the code I am using:

using (SPLimitedWebPartManager wpManager = web.GetLimitedWebPartManager("SitePages/" + pageName, PersonalizationScope.Shared))
    SPList list = web.Lists["List"];

    XsltListViewWebPart wp = new XsltListViewWebPart();
    wp.ListName = list.ID.ToString().ToUpper();
    wp.ViewGuid = String.Empty;

    wpManager.AddWebPart(wp, "Rich Content", 0);


    foreach (System.Web.UI.WebControls.WebParts.WebPart webPart in wpManager.WebParts)
        if (webPart is ListViewWebPart && webPart.Title.Equals("My webpart"))
             var listViewWebpart = webPart as ListViewWebPart;
             var view = list.Views[new Guid(listViewWebpart.ViewGuid)];

             view.Query = @"<Where><Leq><FieldRef Name='DateTime'/><Value Type='DateTime'><Today /></Value></Leq></Where><OrderBy ><FieldRef Name='Modified' Ascending='false' /></OrderBy>";
             view.RowLimit = 1;

Please let me know if I am missing out something. Any suggestion will be of great help. Thanks in advance.

Regards, Ankita

2 Answers 2


You have to create a separate view for this. You can mark it as hidden if you don't want users to see it.

I experienced the same issue, and this seems to be the only work around.

By the way, if you investigate how SharePoint manages list views deployed to separate pages, you will see exactly the same behaivor: a new view is created and marked as hidden, and then any new changes are applied to this view.

The code:

// list - SPList object

var newView = list.DefaultView.Clone(list.DefaultView.Title, list.DefaultView.RowLimit, list.DefaultView.Paged, false);
newView.Query = @"<Where><Leq><FieldRef Name='DateTime'/><Value Type='DateTime'><Today /></Value></Leq></Where><OrderBy ><FieldRef Name='Modified' Ascending='false' /></OrderBy>";
newView.Hidden = true;

var xlv = new XsltListViewWebPart();
xlv.ListName = list.ID.ToString("B");
xlv.ViewGuid = newView.ID.ToString("B");
manager.AddWebPart(xlv, "Rich Content", 0);

(this exact code was not tested, but it is based on the 100% working code we use in production)


You can add the view at the time of instantiating the webpart rather than looping through all webaprts on the page and finding the webpart you need. Also your query seems to be incorrect, try removing Where clause from the query. You may also find this link useful.

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.