Get a listitem by ID
Fetching a listitem by ID will generate an error, if the a listitem with the ID does not exist. To avoid this exception, you can get a listitem by id by searching for it:
private SPListItem GetListItem(SPList List, int ListItemID) { try { string defaultView = List.DefaultView.Title; SPQuery query = new SPQuery(List.Views[defaultView]); string caml =String.Format("
", {0}
ListItemID); query.Query = caml; SPListItemCollection results = List.GetItems(query); if (results.Count == 1) { return results[0]; } } catch (Exception ex) { _ErrorMessage +=
String.Format(“List "{0}" does not contain an item with the id "{1}".
{2}",
List.Title, ListItemID, ex.Message); } return null; }
If there is no listitem with the specified ListItemID, you will get a null instead of an exception.