Karine Bosch’s Blog

On SharePoint

The ListViewByQuery Control


Introduction

The ListViewByQuery control renders a list view on an application page or within a web part based on a specified query.

listviewbyquery

When the control is displayed users can sort on the columns of the list view and apply filters. But all these events need to be implemented by you otherwise the rendering will fail with an ugly error.

Syntax

The ListViewByQuery control  is part of the Microsoft.SharePoint.dll and is located in the Microsoft.SharePoint.WebControls namespace. You can use this control declaratively when developing application pages or control templates:

<spuc:ListViewByQuery ID="CustomersListViewByQuery" runat="server" Width="700px" />

But there is a caveat: the properties List and Query only accept objects and cannot be set declaratively, only in code.

Don’t forget to add a directive at the top of the application page or control template:

<%@ Register TagPrefix="spuc" Namespace="Microsoft.SharePoint.WebControls"
             Assembly="Microsoft.SharePoint, Version=12.0.0.0, Culture=neutral, PublicKeyToken=71e9bce111e9429c" %>

If your are developing a web part you have to create the ListViewByQuery control completely in code:

private ListViewByQuery CustomersListViewByQuery;
private void EnsureChildControls()
{
     CustomersListViewByQuery = new ListViewByQuery();
     // The rest of the code follows here....
}

There are two mandatory properties that need to be set: the List property which is of type SPList and the Query property which is of type SPQuery. The OnLoad event handler or the EnsureChildControls method then contains following code:

list = SPContext.Current.Web.Lists["Customers"];
CustomersListViewByQuery.List = list;
string query = null;
if (!Page.IsPostBack)
{
    query = "<OrderBy><FieldRef Name='Title' Ascending='true' /></OrderBy>";
}
else
{
    // apply filtering and/or sorting
}
SPQuery qry = new SPQuery(list.DefaultView);
qry.Query = query;
CustomersListViewByQuery.Query = qry;

The query object must be instantiated based on an existing view of the list otherwise the ListViewByQuery control will not work. The data displayed by the control is determined by the CAML query itself.

You can limit the number of rows returned by setting the RowLimit property of the SPQuery object:

qry.RowLimit = 50;

This was the easy part but it becomes more complex when you need to implement sorting and filtering. When the user chooses to sort or to filter, the page is posted back with some extra information stored in the HttpRequest object.

Sorting

The user can decide to sort on a certain column by clicking the column header and choosing A on Top or Z on Top.

listviewbyquery-sort2

This instructs the page to post back, and the selected column and sort order is passed to the server stored into the Context.Request[“SortField”]  and the Context.Request[“SortDir”]. Following code sample calls the BuildSortOrder method and passes both constructs the <OrderBy> clause based on both request values.

if (!Page.IsPostBack)
{
    query = "<Query><OrderBy><FieldRef Name='Title' Ascending='true' /></OrderBy></Query>";
}
else
{
    // apply filtering and/or sorting
   if (this.Context.Request != null && this.Context.Request["SortField"] != null)
   {
       string sortorder = BuildSortOrder(this.Context.Request["SortField"],
           (this.Context.Request["SortDir"] == "Asc" ? "true" : "false"));
       if (string.IsNullOrEmpty(query))
           query = sortorder;
       else
           query += sortorder;
   }
}

Following code sample constructs the <OrderBy> clause based on both request values:

private string BuildSortOrder(string fieldName, string sortOrder)
{
    string query = null;
    if (!string.IsNullOrEmpty(fieldName))
    {
        query = string.Format("<OrderBy><FieldRef Name='{0}' Ascending='{1}' /></OrderBy>", fieldName, sortOrder);
    }           
    return query;
}

Filtering

The user can also filter the data in the ListViewByQuery control. When the different values in one of the columns is not a large set of data, the user can select from a list of distinct values.

 listviewbyquery-filter

When the page is posting back after the user action, the selected field is stored in the Context.Request[“FilterField1”] and the selected value is stored in the Context.Request[“FilterValue1”]. If more than 1 filter criteria is specified by the user (by selecting a value of a second column) key/value pairs are added with FilterField2 and FilterValue2 as key, and so on.

Constructing the Where clause of a CAML query is not that easy. I give you the code sample to give you an idea on how you can proceed:

private string BuildFilter()
{
    string query = "{0}";
    bool isFound = true;
    int counter = 1;
    while (isFound)
    {
          string filterfield = "FilterField" + counter.ToString();
          string filtervalue = "FilterValue" + counter.ToString();
          if (this.Context.Request[filterfield] != null && this.Context.Request[filtervalue] != null)
          {
               // Field type must be treated differently in case of other data type
               if (counter > 1)
                   query = "<And>" + query + "{0}</And>";
               query = string.Format(query, string.Format("<Eq><FieldRef Name='{0}' /><Value Type='Text'>{1}</Value></Eq>",
                       this.Context.Request[filterfield], this.Context.Request[filtervalue]));
               counter++;
          }
          else
          {
               isFound = false;
          }
    }
    if (!string.IsNullOrEmpty(query))
       query = "<Where>" + query + "</Where>";
    return query;
}

As one of my readers pointed out, this code snippet only works for text fields. If you want to filter on other types of fields, like number fields, choice fields or lookups, you will have to change the Type attribute from the Value element into the correct type.  To get hold on the field type, you will have to retrieve the field from the list.

SPField field = list.Fields[filterfield];

And change the query statement accordingly:

query = string.Format(query, string.Format("<Eq><FieldRef Name='{0}' /><Value Type='{1}'>{2}</Value></Eq>",
                       this.Context.Request[filterfield], field.TypeAsString, this.Context.Request[filtervalue]));

Grouping

With the ListViewByQuery control you can also build a view where the data is grouped. In that case you have to use the CAML GroupBy element:

query = "<GroupBy Collapse='FALSE'><FieldRef Name='CountryRegionName' /><FieldRef Name='City' /></GroupBy>";

This sample code groups the data by the CountryRegionName and then by City. You can specify more than one group by criterium but the choice of showing the groups collapsed or expanded must be set for all groups by using the Collapse attribute of the GroupBy element.

listviewbyquery-expanded

Use the + and – signs to expand and collapse the different groups.

If you decide to show the groups expanded, you set the Collapse attribute to TRUE and you get the following view:

listviewbyquery-collapsed

But then there is a small problem: you can expand all groups, except the latest one: it shows a Loading label but nevers shows the data.

listviewbyquery-collapsed-expanding

When taking a look at the rendered HTML you can see that all of the hyperlinks that have to do with the ListViewByQuery contain a call to the ExpCollGroup javascript call, which is a function in one of the javascript files that come with SharePoint.

Thanks to one of my readers, Alex, we can now solve this problem with a small piece of javascript. First set the Collapse attribute to FALSE and place your ListViewByQuery control in a DIV and give this DIV an ID. Immediately after the DIV  add the following javascript: 

<div id="ViewDiv" class="ms-authoringcontrols" style="width:700px">
     <spuc:ListViewByQuery ID="CustomersListViewByQuery" runat="server" Width="700px" />
</div>
<script language="javascript">
    ExpLinkFormer = function(divId)
    {
         this._DivId = divId;
         this._init();
    }
    ExpLinkFormer.prototype = {
        _init: function() {
            var div = document.getElementById(this._DivId);
            var links = div.getElementsByTagName("a");
            for (var i = 0; i < links.length; i++) {
                if (links[i].href == "javascript:" && links[i].onclick.toString().indexOf("ExpCollGroup") > -1) {
                   //alert(links[i]);
                   links[i].click();
                }
            }
        }
    }
    var expLnk = new ExpLinkFormer('ViewDiv');
</script>   

The ListViewByQuery control loads with all groups expanded but when it is rendered to the page, the click method is executed on all hyperlinks that have a call to  ExpCollGroup in their href attribute.

81 Comments »

  1. Karine, thanks!

    One question: what about GroupBy?
    When you send GroupBy criteria to the CAML query its showing the groups and the number of documents in those groups but when you click on the expansion icon it just sits there and says loading…

    Do you know solution?

    Comment by Alex | March 25, 2009 | Reply

  2. Thanks for the input. I’ll take a look at GroupBy tomorrow and I’ll let you know in the comments of this page.
    Karine

    Comment by Karine | March 26, 2009 | Reply

  3. Is there any news? I think to solve GroupBy problem we need to use JS.. like a ListViewWebPart

    Comment by Alex | March 31, 2009 | Reply

  4. […] The ListViewByQuery Control […]

    Pingback by The ListViewByQuery Control « Karine Bosch’s Blog | April 7, 2009 | Reply

  5. thanks

    Comment by prijatu | May 19, 2009 | Reply

  6. Nice article! I was able to use the sorting and it works absolutely fine! But with filtering I think BuildFilter() method has to be modified

    1.filterfield has to be changed to filtervalue (second parameter in the AND condition)

    if(this.Context.Request[filterfield] != null && this.Context.Request[filterfield] != null)

    has to be modified as

    if (this.Context.Request[filterfield] != null && this.Context.Request[filtervalue] != null)

    2. I believe has to be changed in the following lines. If the field is of type
    ‘Choice’ or any other the below code is not working

    query = string.Format(query, string.Format(“{1}”,
    this.Context.Request[filterfield], this.Context.Request[filtervalue]));

    Can you please update the above code to grab the type of the field dynamically?

    Thanks,
    Susheel

    Comment by Susheel Dakoju | June 19, 2009 | Reply

  7. Susheel,
    Thanks for your comments! I really appreciate!
    I’ll try your tips out as soon as possible, and I’ll modify/complete the post if necesseray.
    Have a nice weekend,
    Karine

    Comment by Karine | June 19, 2009 | Reply

  8. All the code works fine, but it seems that part of the default behavior in standard lists is lost. For instance, when filtering in a standard list I can see a little funnel symbol on top of the column being filtrated and also the context menu “Clear filter on…” is enabled. This simply doesn’t happen in my code when creating a ListViewByQuery control. I can see the rows filtered, but then I cannot clear the filter, etc. Am I missing something?

    Thanks in advance.

    Manu Moro

    Comment by ManuMoro | June 21, 2009 | Reply

  9. Hi Manu,
    You’re right that some standard behavior like “Clear filter on…” and some other things are not working with ListViewByQuery. I was not able yet to figure that out to make it working.
    Kind regards,
    Karine

    Comment by Karine | June 22, 2009 | Reply

    • Hi Karine
      thanks for your great blog post. The issue that “Clear filter on” is disabled still hasn’t vanished, even after insalling the Oct 2010 sharepoint hotfix. Would you have any idea on how to handle this? Haven’t found anything after researching the whole ListViewByQuery class.

      Comment by Dirk | February 21, 2011 | Reply

  10. I have a question. I have been working with the ListViewByQuery and have gotten it to work with most views. I am having a hard time getting it to work with a Calendar View. It works fine with All Events and Current Events in a calendar list but not the Calendar view. Has anyone else experienced this?

    Comment by DCP | August 10, 2009 | Reply

  11. Thanks for the code!

    One problem: using the RowLimit property limits the rows but how do I get the paging view to click to the next 50?
    And a second problem:
    For the filters the list elements are used, not the elements from the query. Is it able to manage that?

    Besides I figured out, that deleting the &View={CDF0B740-0464-4489-B744-14024AB968A8} or similar from the URL actvates the Clear Filter context menu, but I didn’t figure out how manipulate the URL by Code.

    Kind regards, Eckart

    Comment by Eckart Reuss | August 12, 2009 | Reply

  12. Eckart,
    For your comment “For the filters the list elements are used, not the elements from the query. Is it able to manage that?”
    I suppose you mean that the DefaultView is always used. You can change this code by passing in the correct view here:
    SPQuery qry = new SPQuery(new Guid(list.Views[viewguid]));
    qry.Query = query;
    CustomersListViewByQuery.Query = qry;

    For your other remarks on paging and clearing the filter, I have no answer yet but I’ll post it as soon as I have.
    Karine

    Comment by Karine Bosch | August 24, 2009 | Reply

  13. Hello,

    thanks, Eckart, for realizing point 11.
    here is the solution, put this code somewhere at the beginning of CreateChildControls method

    if (!String.IsNullOrEmpty(this.Page.Request.QueryString[“View”]))
    {
    string strPageQS = “View=” + this.Page.Request.QueryString[“View”];
    string strPageUrl = this.Page.Request.Url.ToString().Replace(“?” + strPageQS, “?a=a”).Replace(“&” + strPageQS, “”);
    this.Page.Response.Redirect(strPageUrl, true);
    }

    Ondra

    PS after several hacks and 3 weeks of HC coding, ListViewByQuery overrides standard list view and has big potential for more features. In MOSS 2010, please, MS, make developer’s life easier!!! ( I doubt it 😉 )

    Comment by Ondra | September 7, 2009 | Reply

    • Many Thanks
      This worked for me

      Comment by Shukraj Khadse | January 15, 2013 | Reply

  14. PSS

    As for paging, i got it working, but you will have to pay for that, it is like 400 lines of code :))

    O. L. / Czech Rep.

    Comment by Ondra | September 7, 2009 | Reply

    • I’d be interested in talking to you on your paging implementation

      Comment by Sean | May 7, 2013 | Reply

  15. Good work Ondra!
    Thanks for posting part of the solution!
    Karine

    Comment by Karine Bosch | September 7, 2009 | Reply

  16. I’m trying to get paging to work with ListViewByQuery but I’m not having any luck. It’s just consistently returning back the exact number of items I specify in the RowLimit property of the SPQuery object.

    Here’s a quick sample of what I’m doing:
    ————————————————————
    Dim ListView as New ListViewByQuery
    Dim List As SPList = web.Lists(“Incident”)
    Dim myQuery As SPQuery
    Dim CollectionPosition As New SPListItemCollectionPosition(“Paged=TRUE&p_IncidentDate=2007%2d05%2d02&p_ID=136&PageFirstRow=6”)

    myQuery = New SPQuery(List.Views(“All Incidents”))
    myQuery.RowLimit = 5
    myQuery.ListItemCollectionPosition = CollectionPosition

    ListView.List = List
    ListView.Query = myQuery
    ————————————————————

    I’m using the SPListItemCollectionPosition object. In this scenario I’m showing 5 items per page, the item with p_ID = 136 is the 5th item in the list, I want to show items 6-10 so I specify &PageFirstRow = 6. This doesn’t work for some reason when the results are rendered to the ListViewByQuery object.

    However, if I call List.GetItems(myQuery). Items 6-10 in the list are returned in the SPListItemCollection.

    What step am I missing to get this to work for ListViewByQuery?

    Thanks,

    -Somsong

    Comment by Somsong | October 23, 2009 | Reply

  17. Thank you for doing such excellent work. Your CAML tool was instrumental in my moving ahead on one of my projects. Keep up the great work. God Bless

    Comment by Dan | October 30, 2009 | Reply

  18. Hi,

    Thanks for this great article. It’s an excellent starting point for ListViewByQuery Control.

    Manitra.

    Comment by Manitra | November 24, 2009 | Reply

  19. Hello Karine,

    This article is very good.I need ur help.
    Actually i have a custom list definition,in the customlist all item.aspx i need GropBy.In all rows in the allitem.aspx page should be groupby with column names.How can i achive this?

    Comment by ahmed | December 22, 2009 | Reply

  20. Actually filtering and sorting is a bit easier than all this.
    I have been playing with ListViewByQuery and this code trying to get filtering working properly but it was always going bonkers.

    To make the filtering/sorting work you don’t actually need any of the code above, you only need to remove the view property from the querystring.
    Place this code at the top of CreateChildControls

    PropertyInfo isreadonly = typeof(System.Collections.Specialized.NameValueCollection).GetProperty(“IsReadOnly”, BindingFlags.Instance | BindingFlags.NonPublic);
    isreadonly.SetValue(HttpContext.Current.Request.QueryString, false, null);
    HttpContext.Current.Request.QueryString.Remove(“View”);
    isreadonly.SetValue(HttpContext.Current.Request.QueryString, true, null);

    Comment by Matt | January 15, 2010 | Reply

    • It pays reading all the comments. Matt this made my day, thanks! This solution solves the filtering issue.
      You will need to add
      using System.Reflection;
      before the namespace, but then it just works great!

      Comment by Dirk | February 21, 2011 | Reply

  21. Thanks for the info Matt,
    I’ll try it out somewhere this weekend, and if your info is correct, I’ll update the post. Thanks again!

    Comment by Karine Bosch | January 15, 2010 | Reply

  22. Exactly what I was after… Thanks!!

    Comment by Kieran | February 3, 2010 | Reply

  23. hi Karine,

    i use filter in ListViewByQuery,but i found “clear filter from ..” function cannot show.

    how do i slove it?

    thank you.

    Comment by eugene | March 27, 2010 | Reply

  24. Thanks for your great articles.
    But I think there are some thing wrong in the code below(Filter):

    if (!string.IsNullOrEmpty(query))
    query = “” + query + “”;

    should be

    if (!queryStr.Equals(“{0}”))
    queryStr = string.Format(“{0}”,queryStr);

    Comment by Wenxuan | May 17, 2010 | Reply

  25. Thank you for providing this article it does contain a lot of great information about configuring a ListViewByQuery.
    Currently I am trying to find a way to add paging and it doesn’t look like it is possible.
    I am not really sure any other way in SharePoint to do this since I like this control will provide the ability to filter and sort so it just seems to complex to use any other method.
    I have tried to pass this into the url:
    ?Paged=TRUE&p_Title=Agelidis&p_ID=11896&PageFirstRow=51
    This doesn’t appear to work on a ListViewByQuery control, but a regular list this does change the page for the content to appear.
    Does anyone have any insight into this and some recommendation how to add paging??

    Comment by Steve | June 10, 2010 | Reply

  26. Hi Steve,
    I know it is possible to add paging, but unfortunately I never found out how.
    Karine

    Comment by Karine Bosch | June 10, 2010 | Reply

  27. Didn’t get chance to read entire post and all the comments ! But if it’s not already posted then, here is the code to take care of Null values i.e. (Empty) filter conditions.
    —————-

    if(string.IsNullOrEmpty(this.Context.Request[filtervalue]))
    {
    query = string.Format(query, string.Format(“”,this.Context.Request[filterfield]));
    }
    else{

    query = string.Format(query, string.Format(“{2}”,
    this.Context.Request[filterfield], “TEXT”,this.Context.Request[filtervalue]));
    }
    —————-

    Thanks,
    Whizsid

    Comment by whizsid | June 16, 2010 | Reply

  28. Karine, 27 and 28 are the same. (You might wanna delete 27th )!

    The reason to post the same comment twice is because I noted that first time it just printed “{2}” in the String.Format(… function. On submitting the comment second time, I realized that tags like lt; Eq gt; were filtered leaving only “{2}”.

    It’s nothing but the same code taken from your function – BuildFilter().

    Thanks.

    Comment by whizsid | June 16, 2010 | Reply

  29. Hi whizsid,
    Thanks for the additional information.
    Karine

    Comment by Karine Bosch | June 17, 2010 | Reply

  30. Hi Karine,
    Any solution to collapse the groups when the web part is rendered? and to enable the clear filter from thing?

    Thanks for the great article. It was really helpful.

    Comment by sach | July 5, 2010 | Reply

  31. I want to add the ListViewByQuery Control into a web part. I did it like this.
    protected override void Render(HtmlTextWriter writer)
    {
    //here i gave the list and view for the control.
    writer.Write(“”);
    view.RenderControl(writer);
    writer.Write(“”);
    writer.Write(“”);
    writer.Write(“ExpLinkFormer = function(divId)”);
    writer.Write(” {“);
    writer.Write(“this._DivId = divId;”);
    writer.Write(“this._init();”);
    writer.Write(” }”);
    writer.Write(“ExpLinkFormer.prototype = {“);
    writer.Write(” _init: function() {“);
    writer.Write(” var div = document.getElementById(this._DivId);”);
    writer.Write(“var links = div.getElementsByTagName(‘a’);”);
    writer.Write(“for (var i = 0; i -1) {“);
    writer.Write(” //alert(links[i]);”);
    writer.Write(” links[i].click();”);
    writer.Write(” }”);
    writer.Write(” }”);
    writer.Write(” }”);
    writer.Write(” }”);
    writer.Write(” var expLnk = new ExpLinkFormer(‘ViewDiv’);”);
    writer.Write(” “);
    }

    My problem is when groups are always expanded when the page loads. Please help.

    Comment by sach | July 8, 2010 | Reply

  32. The individual context menu is not working. I have added listviewbyquery on custom webpart. Is there any solution to get the context menu working?
    The javascript message that pops up when i click on the context menu is:
    This item is no longer available. It may have been deleted by another user. Click Ok to refresh page

    Comment by Pragnesh | August 24, 2010 | Reply

    • Hi, great post. I am trying to use this control as a custom webpart in 2010, I am getting the same issue as Pragnesh wherby the context menu does not work. I have tried debugging the xslt and see that the ctx. object that is declared in the javascript is different, this is used to build the JSON callback, as the table ID is not found in the JSON, the user is told that the item no longer exists.

      I wonder if Pragnesh or yourself hnow how to resolve this?

      Thanks in advance.

      Duncan

      Comment by Duncan | October 13, 2010 | Reply

      • The hotfix below seems to address this issue.
        http://support.microsoft.com/kb/2405789

        Thanks,
        Moninder

        Comment by Moninder | November 15, 2010

      • The hotfix fixed the ECB menu but you will get a security validation error when you try to delete a item. Anyone have solution for that? Thanks.

        Comment by kevin | January 20, 2012

  33. OMG, Thank you so much Matt for your post (#20). Simply removing the View parameter from the query string makes everything work like a charm! Sorting, filtering, even adds the small icons that tell you the column is sorted/filtered. Also enables the Clear filters option.

    This just made my day and it’s not even noon yet, thanks again! Thanks to Karine for this blog also, great work!

    Comment by JP Lambert | September 30, 2010 | Reply

  34. Hi, I have been trying to use this the ListViewByQuery control on a subsite to display a list from the parent site. It seems to support standard list views fine, however I cannot get the DataSheet view to display on the child site. Is the DataSheet View support for this.

    Thanks,
    Moni

    Comment by Moninder | December 30, 2010 | Reply

  35. Hi,
    this post has been very useful for me but now i want to add the paging feature to my listviewby query and i don’t know how.

    is there anyone who has achieved it?

    thanks

    Comment by Josep | January 14, 2011 | Reply

  36. if we used this web part in page and re customized it using SPD and try to make A connection with Custom list form is this work

    Comment by mustafa | February 8, 2011 | Reply

  37. Hi,

    Nice post. Is their any way to clear the view. Actually I am looking to clear the value from ListViewByQuery and then populate it again.

    –Sujeet

    Comment by Sujeet | February 25, 2011 | Reply

  38. Im proberbly stupid but I cant get this to work. I get a “Error Rendering Control – MyListViewByQueryName An unhandled exception has occured. Object reference not set to an instance of an object.

    What am I doing wrong?

    Comment by Martin | March 23, 2011 | Reply

  39. In jquery

    $(document).ready( function(){
    $(‘#viewDiv’).find(‘a[onclick*=ExpCollGroup]:even’).each(
    function(){
    this.onclick();
    }
    );
    });

    Comment by Jonesbeach | April 6, 2011 | Reply

    • Wished I spotted this one earlier saved me the trouble of figuring it out, I made mine a little more complicated, wasnt sure I could rely on that, but actually yours makes more sense than mine

      $(‘#viewdiv td a[onclick*=”ExpCollGroup”] img’).parent().each(function() { $(this).click(); }); });

      This, as does yours, as does the original , clicks every button, if you have a double grouping then you only need to click the layer 1 groups, but I’d had enough by this point. without a Regex (i know theres yet another plugin) I couldnt filter by the “td titlen-n_1_$” where n1 is the ctxid and n2 is the Level1 count.

      Would be great if someone could figure out a better selector to select only L1 clicks

      Comment by Binary Jam | July 13, 2011 | Reply

  40. Hi all,
    I have this problem.. 2 list: States (Name) and Cities (Name, State).. I use the listViewByQuery control to show the States wich have not a city.. the problem is that I have 400 Cities so the query is too long and the listViewByQuery return
    .. any ideas?
    Tnks

    Comment by tantononrispondo | May 9, 2011 | Reply

  41. Hi Karine,
    Your blog is one of my favorite blog which I always likes to bookmark your posts.
    I am using ListViewByQuery control, but the sorting logic is not executing as expected.
    When I click on header column, it always loads SortOrder=Asc. It never goes to Dsc in the whole life time, no matter what how many times we have clicked the header column.
    Any suggestions where am I doing mistake?

    I have added all my logic in CreateChildControls(), and then moved code to OnLoad and then moved to EnsureChildControls(), nothing works.
    The question in my mind is, how it detects the last sort order action? It should save somewhere right like ViewState etc… Because I am using plain web part which recreated when page loads everytime, it losts that data. So, everytime it is loading Asc instead of Dsc next time.

    thanks
    -Praveen.

    Comment by Praveen | June 14, 2011 | Reply

  42. Hi Praveen,
    Thanks for reading my blog!
    I have 2 questions for you:
    – are you using SharePoint 207 or SharePoint 2010?
    – Did you add some code behind as explained in the Order section?
    Karine

    Comment by Karine Bosch | June 14, 2011 | Reply

  43. Hi Karine,
    Awesome blog. I tried this to query shared documents from a different collections.
    It display the list nicely but I can’t get the “Add New Document” link to show up.
    Any idea how to do that?

    Cheers!!

    Comment by Sariman | July 6, 2011 | Reply

  44. This has dug me out of a hole, but this control still has problems. My encapsulation of this control allows the user to pick the list and view and in my fix I regex the collapse out the query.

    I discovered if you add two onto the page then each one has a ctxid of 1, when it renders the table the ID’s of the table (and subsequently how it references each level for the click events) uses that ctxId as part of all other Id’s. As both Controls are ctxid=1 then clicking on items in WebPart 2 effect the tree in Webart 1

    Not Good.

    I tried using the ListViewPart instead encapsulated within my part, but this too, did not work, it failed to keep track of the ctxId’s, it’s client side code was correct in this case but the server side responses returned the wrong ctxId’s. So I returned to the ListViewByQuery and for now, hope no-one sticks two on a page.

    Later on I might try and grab the rendered output and regex all the ctxIds and table Ids to match, somewhere in the 100’s and try and register the ctxid somewhere in the page/thread so other of my parts know which number they are.

    Comment by Binary Jam | July 13, 2011 | Reply

  45. 44.Hi Karine,
    Awesome blog. I tried this to query shared documents from a different collections.
    It display the list nicely but I can’t get the “Add New Document” link to show up.
    Any idea how to do that?

    Cheers!!

    Comment by ss | July 22, 2011 | Reply

  46. I can do grouping at two levels successfully. For third attempt it is giving err: render failed . Any suggestion?

    Comment by shweta | August 29, 2011 | Reply

  47. Hi all,
    Can someone help me understand while when executing this query
    “3”+
    “[Today+12Day(s)]”+
    “”+
    “3[Today+12Day(s)]”+
    “[Today-4Day(s)]”

    in the CALM query tool
    it returns one item as expect but when running in code (in a console application it return 5 items while in a sharepoint job nothing at all).
    thank,

    Comment by Joel | December 6, 2011 | Reply

  48. someone solve the paging issue removing the View parameter from the querystring. Here is the link:

    Sorting, filtering and paging in ListViewByQuery

    Comment by jorge | March 2, 2012 | Reply

  49. I attempted to create this webpart by using LINQ to retrieve the data but I found that the performance was really slow. So I rewrote the code to use CAML instead and the performance was dramatically improved. Just want too see if anyone else has experienced a similar situation?

    Comment by Sydney SharePoint consultant | March 31, 2012 | Reply

  50. Hi, it is known that LINQ for SharePoint is not the most performing way of retrieving data, CAML is still the preferred way.

    Comment by Karine Bosch | April 4, 2012 | Reply

  51. Dear Karine, I am newbie in SP development. I tried to implement ListViewByQuery on custom app page, but receive following error:
    My code behind is:
    public class ListView : LayoutsPageBase{
    protected SPList list;
    protected ListViewByQuery CustomersListViewByQuery;

    protected override void OnLoad(EventArgs e)
    {
    list = SPContext.Current.Web.Lists[“Customers”];

    CustomersListViewByQuery = new ListViewByQuery();
    CustomersListViewByQuery.List = list;
    string query;
    if (!Page.IsPostBack)
    {
    query = “”;
    }
    else
    {
    // apply filtering and/or sorting
    }

    SPQuery qry = new SPQuery(list.DefaultView);
    qry.Query = query;

    CustomersListViewByQuery.Query = qry;
    }
    }

    aspx page snippet:

    The error:
    One or more field types are not installed properly. Go to the list settings page to delete these fields. at Microsoft.SharePoint.Library.SPRequestInternalClass.GetListItemDataWithCallback(String bstrUrl, String bstrListName, String bstrViewName, String bstrViewXml, SAFEARRAYFLAGS fSafeArrayFlags, ISP2DSafeArrayWriter pSACallback, ISPDataCallback pPagingCallback, ISPDataCallback pSchemaCallback)
    at Microsoft.SharePoint.Library.SPRequest.GetListItemDataWithCallback(String bstrUrl, String bstrListName, String bstrViewName, String bstrViewXml, SAFEARRAYFLAGS fSafeArrayFlags, ISP2DSafeArrayWriter pSACallback, ISPDataCallback pPagingCallback, ISPDataCallback pSchemaCallback)

    What am I doing wrong?

    Thanks in advance,
    Emiliya

    Comment by Emiliya | April 6, 2012 | Reply

  52. aspx page snippet again:

    Comment by Emiliya | April 6, 2012 | Reply

  53. Sorry for my post. I googled that the problem was in my query. I used display name instead of internal name for quering a column.

    Comment by Emiliya | April 6, 2012 | Reply

  54. Hi Kariine

    Thanks for this beatiful blog.
    Could you please let me know that Can I make group by columns more than 2 and want to display all the items without paging. is that be possible?

    Please suggest

    Comment by Niyaz | June 19, 2012 | Reply

  55. Hi Karine,

    I trired group by 2 columns but if possible to user more than 2. please help us

    Thanks
    Sathish

    Comment by Sathish Kumar | August 7, 2012 | Reply

  56. Hi Karen,
    Great post!!
    However, I am looking for similar solutions on Grouping (Expanding/Collapsing) and Paging for WEBPARTs (cs files only). Can you help me on this?

    Comment by SZG | November 12, 2012 | Reply

  57. […] The ListViewByQuery Control « Karine Bosch’s Blog […]

    Pingback by Resources: SharePoint Development,Programming And PowerShell | lionadi | March 18, 2013 | Reply

  58. Hi! is there any way to add the totals by adding the tab?
    I’ve tried this, but it’s not working for me! any ideas?

    Comment by Nicole | June 5, 2013 | Reply

  59. Sorry about my previous post, I intended to paste my code, but it seems that the forum didn’t like that.
    I was trying to add the tag Aggregations with the FieldRef Name=”LinkFilename” Type=”COUNT”
    to the view’s schema but it’s not working at all

    do you know if this is even possible or if there’s another way of doing this?

    Tank you very much!!!

    Comment by Nicole | June 5, 2013 | Reply

  60. Thanks for this! Much appreciated. Wish I knew about ListViewByQuery earlier. #DataViewWebPart

    Comment by Peter | March 12, 2014 | Reply

  61. hi Karine , thnx for the great article.
    1)i would like to know how to implement paging in this control.
    2) also on the context menu, i have to hide/remove the “Workflows” menu item as i am not using any workflows/ publishing feature in my site collection.
    for this,i went to core.js file and found that there is a function called addworkflowstomenuitem() {}

    AddWorkflowsMenuItem(d,a) = function() { }

    so i added in my hidden content editor web part so that it hides the Workflows menu item.
    but this happens only in when the page is in EDIT mode , and it doesnt hide when the page is in normal mode.
    pls help if you can throw some light on this.

    Comment by SamolPP | June 9, 2014 | Reply

  62. Hi! In query I wrote query.RowLimit = 50, when the control load, only 50 rows first displays and NO Paging button is displayed.
    Could anyone give me help.
    Many Thanks,

    Comment by Linda | November 27, 2014 | Reply

    • Hi Linda,
      Isn’t this expected behavior? You put the rowlimit to 50, which makes the query return only 50 rows. The 50 rows are all shown on the page, so no paging control is displayed.
      Kind regards,
      Karine Bosch

      Comment by Karine Bosch | November 27, 2014 | Reply

      • Hi Karine Bosch,

        My List has 40 thousand records, in listviewbyquery I have to put pagination. 50 rows per page. Therefore In query I wrote query.RowLimit = 50. But when control load, only the first 50 rows are shown, No paging control such as 1 2 3….80 are shown.
        Do you know how to make paging control in listviewbyquery
        Many thanks.

        Comment by Linda | November 27, 2014

      • Hi Linda,
        As specified in my previous reply, the RowLimit LIMITS your results to 50 rows. But paging is difficult to achieve with the ListViewByQuery control, it’s not out of the box. This is the most helpful post I found: http://sharepoint.stackexchange.com/questions/42040/paging-with-listviewbyquery-in-web-part
        I hope this helps.
        Karine

        Comment by Karine Bosch | November 27, 2014

  63. Hi Karin,

    First of all great post 🙂

    I’m currently struggeling with custom field Types and the ListViewByQueryControl.

    I have create a custom field type to display an alternate title as link to document, the field itself works fine in the normal list view and will be rendered as link.
    But if I use my View with ListViewByQueryControl it will always be displayed as Text and it seems the customized rendering for this field type will never be called.

    Do you have any experience with this? Or any tipps how to troubleshoot?!

    Comment by Nadine Storandt | March 15, 2016 | Reply

    • Hi Nadine,
      Thanks for reading my blog.
      Unfortunately, that’s one of the issues with custom fields: they do not render as intended in certain circumstances. In SharePoint 2013 you can perhaps solve this issue with JSLink. Which version of SharePoint are you working with?
      Kind regards,
      Karine Bosch

      Comment by Karine Bosch | March 16, 2016 | Reply

      • Hi karin,

        I’m working with SharePoint 2013 and already tried it with JSLink but this will also not rendered when working with this ListViewByQueryControl.
        Or did I missed something during implementation where I need to specify the js?

        Comment by Nadine Storandt | March 16, 2016

      • Hi Karin,

        now I have it working 🙂

        But not with JSLink I used the property CAMLRendering on my custom field type and entered there the Render DisplayPattern. After that it started to working.
        Hope it helps anyone who is also struggeling with this.

        Comment by Nadine Storandt | March 16, 2016

      • Hi Nadine,
        That’s a nice work around!
        Kind regards,
        Karine

        Comment by Karine Bosch | March 30, 2016


Leave a reply to Joel Cancel reply