Get a listitem by ID

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("<Where><Eq><FieldRef Name='ID'/><Value Type='Counter'>{0}</Value></Eq></Where>",
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}\".<br/>{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.

Leave a Reply