5

I have a peculiar issue, following is the code :

var item = list.Items[ID];

The problem is that the returned item is actually the Items[ID-11]. I can verify that from dispitem.aspx?id=[ID]

Since the items start with ID = 11 (some items have deleted), it looks like the ID is actually a counter and not item's ID.

6

get the item in SPlistitem and then get value from it. For ex =

Splistitem item = list.getitembyid(1);
var x = item.ID;
6

In SharePoint ID is a counter and always incremental. Even though you delete item, it is never going to occupy the blank ID. It always keeps on incrementing.

Also list.Items always return SPListItemCollection. But when you delete the item from List, the index of Item keeps on changing. For example, you had 10 items in list list.Items[9] will give you the item with ID = 10. But if you delete two items lets say ID equals 5 & 6. Than list.Items[9] will throw an error, while list.Items[7] will give you item with ID = 10.

To get the item from SPListItemCollection using ID try the following code.

SPList list = web.Lists.TryGetList("List title");
SPListItemCollection itemColl = list.Items;
SPListItem item = itemColl.GetItemById(id);

In this way you'll always get the item you require.

2

list.Items[ID]; (th variable named ID is probably not the best here to understand it, index would be better) is a pure C# syntax: that's an array indexer (zero-based).
It's used to access an in-memory collection of ordered objects. [index] has nothing to do with SharePoint, and when calling this code .NET we simply access an array of ordinary objects already populated into the array. It has no awareness of SharePoint at this time.
SharePoint did the actual SharePoint job (requesting the DB, etc.) when .Items was called the first time on this list. It got all the items of the list (mind the performances if you have more than ~10s items...) and populates the array. From there, the index in the array has nothing to do with the ID of the items.

As others mentioned, use list.GetItemById(ID); to retrieve a specific item whose ID is known. And this will give you much better results regarding performances (only one item retrieved from SQL and loaded into memory).

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.