0

I am using the following Caml Query to get data from a share point list.

    oSb.Append("         <OrderBy>")
    oSb.Append("              <FieldRef Name=""Title"" />")
    oSb.Append("         </OrderBy>")

But this query is giving me all columns of list. Is there any way to get only desired column from a share point list using Caml Query? Please help me.

user1369925
  • 55
  • 2
  • 4
  • 12

1 Answers1

4

Take a look at the MSDN article about View Fields. You can specify those fields before running your CAML query.

using (SPSite site = new SPSite("http://localhost"))
     {
        using (SPWeb web = site.OpenWeb())
        {
           // Build a query.
           SPQuery query = new SPQuery();
           query.Query = string.Concat(
                          "<Where><Eq>",
                             "<FieldRef Name='Status'/>",
                             "<Value Type='CHOICE'>Not Started</Value>",
                          "</Eq></Where>",
                          "<OrderBy>",
                             "<FieldRef Name='DueDate' Ascending='TRUE' />",
                             "<FieldRef Name=’Priority’ Ascending='TRUE' />", 
                          "</OrderBy>");                    

           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"]);
           }
        }