0
votes

I am trying to query list items using caml (first time doing this) and sort the items based on modified date so I can get access to most recent documents. However when trying to get the SPListItem based on the ID I am failing.

Code:

SPQuery query = new SPQuery();
String camlquery = "<OrderBy><FieldRef Name='Modified' Ascending='False' /></OrderBy>";                        
query.ViewAttributes = "Scope = 'Recursive'";
query.ViewFields = "<FieldRef Name='Modified' /><FieldRef Name='Title' /><FieldRef Name='Name' />";
query.Query = camlquery;
query.IncludeMandatoryColumns = true;
SPListItemCollection col = list.GetItems(query);


//failing here... I think   
SPListItem item = col.GetItemById(0);

Is there a way to get an SPListItem based on its index from within the SPListItemCollection?

I have tried

SPListItem item = col[0];

Also with no luck.

Here is the error I am getting:

Value does not fall within the expected range. Description: An unhandled exception occurred during the execution of the current web request. Please review the stack trace for more information about the error and where it originated in the code.

Exception Details: System.ArgumentException: Value does not fall within the expected range.

2
Have you checked that the collection does contain items? If you get an error "Value does not fall within the expected range" on command like col[0] It usually means an empty array.banana

2 Answers

0
votes

If you want to get a SPListItem using Id then you do not need to go for caml, try this,

 SPSite oSite = new SPSite("http:/MyTestSite/");
 SPWeb oWeb = oSite.OpenWeb();
 SPList oList = oWeb.Lists["MyCustomList"];

 SPListItem oListItem = oList.Items.GetItemById(1);

But If you insist on getting it by using caml, make sure you include Id in your ViewFields caml query.

And get the items using Id as :

foreach (ListItem item in col)
{
    if(item["Id"] == 1) //Only an example
    {
        var itemFromId = item;
    }
}

Also to note, The value of the ID property is not the same as the index of the item in the collection of list items. This property contains the item's 1-based integer ID, which is one greater than the ID of the item that was previously added. If the item is deleted, its ID is not reused.[MoreInfo]

0
votes

The issue was with the collection that I was returning. I had to make sure there were results prior to using the item:

if (col.Count > 0)
{
SPListItem item = col[0];
}

Silly mistake.