Wednesday 12 August 2015

Check if ListItem exist in SharePoint List by Id

We can get SPListItem by id directly using the method

list.GetItemById(id)

But if the item with given id does not exists then the above given method will throw an exception as it will not get the item of given id.

Hence, before getting the id we can check whether the ListItem of given id exists or not using LINQ query as given below

int count = (from SPListItem item in list.Items
                    where Convert.ToInt32(item["ID"]) == id
                     select item).Count();

The above code will return the count if the item with given id exists. If the item does not exist then it will return 0.

Based on the count you can proceed with further execution.

1 comment: