Question

I am using the following code display items in list but it is not sorting them. No matter what I write in order by clause, it always brings the same results.

SPListItemCollection items = null;
using (SPSite site = new SPSite(SPContext.Current.Site.Url))
{
     using (SPWeb web = site.OpenWeb("mysite"))
     {
          SPList list = web.Lists["Pages"];
          SPQuery query = new SPQuery();
          query.Query = "<ViewFields><FieldRef Name='Title' /><FieldRef Name='Created' /><FieldRef Name='LinkFilenameNoMenu' /></ViewFields><OrderBy><FieldRef Name='Created' Ascending='TRUE' /></OrderBy><QueryOptions><RowLimit>5</RowLimit></QueryOptions>";
          items = list.GetItems(query);
          foreach (SPListItem lst in list.Items)
          {
               label1.Text += "||"+ lst["Title"].ToString() ;
          }
     }
}
Was it helpful?

Solution

The syntax of CAML query is not correct, you cannot use ViewFields element in the query property neither QueryProperties element

Use SPQuery.ViewFields property to specify view fields. Use SPQuery.RowLimit property to specify that constraint as well.

And you use all list items in the foreach loop, not the items you get by that query. Your code should look something like this:

SPListItemCollection items = null;
using (SPSite site = new SPSite(SPContext.Current.Site.Url))
{
     using (SPWeb web = site.OpenWeb("mysite"))
     {
          SPList list = web.Lists["Pages"];
          SPQuery query = new SPQuery();
          query.Query = "<OrderBy><FieldRef Name='Created' Ascending='TRUE' /></OrderBy>";
          query.RowLimit = 5;
          query.ViewFields = "<FieldRef Name='Title' /><FieldRef Name='Created' /><FieldRef Name='LinkFilenameNoMenu' />";
          items = list.GetItems(query);
          foreach (SPListItem lst in items)
          {
               label1.Text += "||"+ lst["Title"].ToString() ;
          }
     }
}

OTHER TIPS

You don't use your query in your foreach.

Try:

foreach(SPListItem lst in items)
{ ... }

I recommend:

foreach(SPListItem item in list.GetItems(query))
{ ... }
Licensed under: CC-BY-SA with attribution
Not affiliated with sharepoint.stackexchange
scroll top