C# – Sharepoint – Filtering lists by userid via CAML

ccamlfilteringsharepoint-2007sharepoint-list

Using Sharepoint 2007 and trying to filter a list of items by a field called StudentName:

<Field
ID="{GUID-REDACTED}"
Name="StudentName"
DisplayName="Student Name"
Type="User"
Group="STUDENT COLS" />

Currently, this is the CAML used to filter, when its run through U2U CAML Query Builder, it returns the correct list items without a problem, however when its deployed to SharePoint, it returns the entire list (i.e. no filtering).

SPQuery userQuery = new SPQuery();
userQuery.Query = "<OrderBy>
<FieldRef Name='Rank'>
</FieldRef>
</OrderBy>
<Where>
    <Eq>
        <FieldRef Name='StudentName' LookupId='TRUE' />
        <Value Type='Integer'><UserID /></Value>
    </Eq>
</Where>"

SPListItemCollection userProjectBasket = PBL.GetItems(userQuery);

I've tried it with and without Query tags, to no avail and i've also changed the type of the userID to User as a last resort, still no joy.

Very stumped, so any input warmly welcomed. Thanks.

Best Answer

The OrderBy caluse needs to come after the Where clause:

userQuery.Query = 
@"<Where>
    <Eq>
        <FieldRef Name='StudentName' LookupId='TRUE' />
        <Value Type='Integer'><UserID /></Value>
    </Eq>
</Where>
<OrderBy>
    <FieldRef Name='Rank'/>
</OrderBy>";
Related Topic