views:

529

answers:

1

I'm trying to get a count of items in a list, based on a view. Every method I've tried so far only returns the grand total of the list. I've tried just about every method I've run across while searching, and everything ends up with the same results.

Here's one of the methods I've tried:

SPWeb web = SPContext.Current.Web;
SPView view = web.GetViewFromUrl("url to my view");
int count = view.ParentList.GetItems(view).Count;

My list has 28 items, but the view I'm referencing filters it and shows four items. I expect my count to be 4, not 28 - but 28 is what I always get.

Here's another method I've tried:

SPSite site = SPContext.Current.Site;
SPWeb web = site.OpenWeb();

SPQuery MyQuery = new SPQuery();
MyQuery.Query = "<Query><Where><Eq><FieldRef Name='strStatus' /><Value Type='Text'>submitted</Value></Eq></Where></Query>";

IEnumerable<SPListItem> results = web.Lists["Requests"].GetItems(MyQuery).Cast<SPListItem>();

// results.Count() is 28...  should be 4

So in this method I'm skipping the view and just trying to pass in a CAML query. When testing my query in U2U, four results are returned as expected...

The larger picture is that I'm doing this inside of my custom menu control's OnMenuItemDataBound event handler. I don't know if that makes a difference at all, but the idea I'm heading towards is that each item that links to a view in a specific list, will show the count of items in that view next to the link.

Any ideas why I'm getting a list total instead of the filtered totals? Thanks!

+1  A: 

If I remind correctly, you need to remove the <Query> from your SPQuery. The CAML Builders use it but its unnecessary in the actual SPQuery. Of course you need to make sure the fields exist.

MyQuery.Query = "<Where><Eq><FieldRef Name='strStatus' /><Value Type='Text'>submitted</Value></Eq></Where>";
F.Aquino
The query is just one way to do it... in the original post I was just showing how I tried to do it by using a view, and by using a query - but still getting the same results.
SeanW
@SeanW, if the Query property of SPQuery is wrong, you will get all the items back. In your demo, strip out the `<Query>` and closing tag `</Query>`. I don't know why CamlQueryBuilder leaves them there, but it makes the syntax of queries wrong, if you simply copy-paste it.
naivists
Oooh, I see what F.Aquino was trying to say now - yes, I remember reading that at some point too. I'm home for the weekend, but will try that first thing Monday morning. Thanks!
SeanW
To add to the confusion, if you are writing xml for web services, the correct syntax is <query><Query><Where>
Tom Clarkson
Thank you, i did not know that. Why does it return all the items? Should throw an exception or return null, if I want all the items I would not user a query.
Gaotter