I have a which displays a variety of items in a based on a SPView.

Additionally, I have implemented a search module which when a keyword is entered should get all items that has a Title which contains a part of the entered keyword, using SPQuery.

Using SPList.GetItems() works fine when using the SPQuery =>

var itemCollection = SPList.GetItems(SPQuery);

The above code gives me the items that I want, but unfortunately also all the ones that I don't want. What I want is to get all items from the SPView which match the entered keyword.

I found out that you could use SPQuery together with SPView =>

var itemCollection = SPList.GetItems(SPQuery, "viewName");

Which sounds pretty good, but when studied closer reveals that the "viewName" should actually be the SPViews ID ToStringed. And that if the SPQuery contains a <Where> clause, the "viewName" overrides that query and just returns every item in that particular view.

So my question, does there exist a way of querying a SPView directly or do I have to make a painful work around?

Solution code

Thank you, Simon Doy, for the hint.

var query = new SPQuery(SPList.GetView(ListViewId))
    Query = string.Format(string.Concat(
                            "<FieldRef Name='Title'/>",
                            "<Value Type='Text'>{0}</Value>",
                            "<FieldRef Name='FieldAutoGeneratedName'/>",
                            "<Value Type='Text'>{0}</Value>",
                        "<FieldRef Name='FieldATTCode'/>",
                        "<Value Type='Text'>{0}</Value>",
            ), param)
var items = SPList.GetItems(query);

Above code returns all items from the specified listview matching the param


How about creating the SPQuery object using the constructor where you can pass the appropriate SPView.


You could then add a query to include the appropriate items, something like:-

var query = new SPQuery(spView); 

query.Query = String.Format("<Where><Eq><FieldRef Name='Title'/><Value Type='Text'>{0}</Value></Eq></Where>", keyword);

SPListItemCollection listItems = oList.GetItems(query);
| improve this answer | |
  • Just realised that the CAML wasn't being displayed. – Simon Doy Jul 30 '13 at 9:54

If the SPQuery returns all the items of the List, then in most cases the QueryString is simply wrong. The (in my optionion weird) default behaviour is, that in case of wrong QueryStrings a Caml-Query returns ALL the items.

For example of a common mistake: The QueryString for SPQuery.Query must NOT include the "<Query>"-Tag. If so, it returns all items and ignores the Where-Clause completely.

| improve this answer | |
  • Hmm, if my query is incorrect, I usually get an exception stating that the query is invalid – Robert Lindgren Jul 30 '13 at 11:23

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy