SPQuery.ViewFields property

Gets or sets the view fields that are returned by the query.

Namespace:  Microsoft.SharePoint
Assembly:  Microsoft.SharePoint (in Microsoft.SharePoint.dll)

public string ViewFields { get; set; }

Property value

Type: System.String
A string that contains a fragment in Collaborative Application Markup Language that specifies the view fields.

The ViewFields property contains a string that corresponds to the inner XML of the ViewFields element in Collaborative Application Markup Language (CAML).

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.

The following example is a console application that uses a query to get a collection of items from the Tasks list and specifies the field values to return with each item. After fetching the data, the application prints a report to the console.

using System;
using Microsoft.SharePoint;

namespace Test
   class ConsoleApp
      static void Main(string[] args)
         using (SPSite site = new SPSite("http://localhost"))
            using (SPWeb web = site.OpenWeb())
               // Build a query.
               SPQuery query = new SPQuery();
               query.Query = string.Concat(
                                 "<FieldRef Name='Status'/>",
                                 "<Value Type='CHOICE'>Not Started</Value>",
                                 "<FieldRef Name='DueDate' Ascending='TRUE' />",
                                 "<FieldRef Name=’Priority’ Ascending='TRUE' />", 

               query.ViewFields = string.Concat(
                                   "<FieldRef Name='AssignedTo' />",
                                   "<FieldRef Name='LinkTitle' />",
                                   "<FieldRef Name='DueDate' />",
                                   "<FieldRef Name='Priority' />");

               query.ViewFieldsOnly = true; // Fetch only the data that we need.

               // Get data from a list.
               string listUrl = web.ServerRelativeUrl + "/lists/tasks";
               SPList list = web.GetList(listUrl);
               SPListItemCollection items = list.GetItems(query);

               // Print a report header.
               Console.WriteLine("{0,-25}  {1,-20}  {2,-25}  {3}",
                  "Assigned To", "Task", "Due Date", "Priority");

               // Print the details.
               foreach (SPListItem item in items)
                  Console.WriteLine("{0,-25}  {1,-20}  {2,-25}  {3}",
                     item["AssignedTo"], item["LinkTitle"], item["DueDate"], item["Priority"]);