Share via


SPQuery Class

Represents a query in a list view.

Inheritance Hierarchy

System.Object
  Microsoft.SharePoint.SPQuery

Namespace:  Microsoft.SharePoint
Assembly:  Microsoft.SharePoint (in Microsoft.SharePoint.dll)
Available in Sandboxed Solutions: Yes
Available in SharePoint Online

Syntax

'Declaration
<ClientCallableTypeAttribute(Name := "CamlQuery", ServerTypeId := "{3d248d7b-fc86-40a3-aa97-02a75d69fb8a}",  _
    ValueObject := True)> _
<SubsetCallableTypeAttribute> _
Public Class SPQuery
'Usage
Dim instance As SPQuery
[ClientCallableTypeAttribute(Name = "CamlQuery", ServerTypeId = "{3d248d7b-fc86-40a3-aa97-02a75d69fb8a}", 
    ValueObject = true)]
[SubsetCallableTypeAttribute]
public class SPQuery

Remarks

The Type attribute is particularly useful for Lookup and User fields. Otherwise, without that attribute, the query may not return the expected results. In some cases, the query may fail completely.

For information about how to use Language-Integrated Query (LINQ) queries to retrieve list items in SharePoint Foundation, see Managing Data with LINQ to SharePoint.

Examples

The following code example displays the titles of items in a Tasks list where the Status column equals Completed. The example uses Collaborative Application Markup Language (CAML) to define the query.

This example requires using directives (Imports in Visual Basic) for the Microsoft.SharePoint and Microsoft.SharePoint.Utilities namespaces.

Dim webSite As SPWeb = SPContext.Current.Site.RootWeb
Dim list As SPList = webSite.Lists("Tasks")

Dim query As New SPQuery()
query.Query = "<Where><Eq><FieldRef Name='Status'/>" + _
  "<Value Type='Text'>Completed</Value></Eq></Where>"
Dim items As SPListItemCollection = list.GetItems(query)

Dim item As SPListItem
For Each item In  items
    Response.Write((SPEncode.HtmlEncode(item("Title").ToString()) + _
      "<BR>"))
Next item
SPWeb oWebsiteRoot = SPContext.Current.Site.RootWeb
SPList oList = oWebsiteRoot.Lists["Tasks"];

SPQuery oQuery = new SPQuery();
oQuery.Query = "<Where><Eq><FieldRef Name='Status'/>" +
    "<Value Type='Text'>Completed</Value></Eq></Where>";
SPListItemCollection collListItems = oList.GetItems(oQuery);

foreach (SPListItem oListItem in collListItems)
{
    Response.Write(SPEncode.HtmlEncode(oListItem["Title"].ToString()) + 
        "<BR>");
}

Thread Safety

Any public static (Shared in Visual Basic) members of this type are thread safe. Any instance members are not guaranteed to be thread safe.

See Also

Reference

SPQuery Members

Microsoft.SharePoint Namespace