SPList.GetItemById Method (Microsoft.SharePoint)
Returns the list item with the specified integer ID.

Namespace: Microsoft.SharePoint
Assembly: Microsoft.SharePoint (in microsoft.sharepoint.dll)
Syntax

Visual Basic (Declaration)
Public Function GetItemById ( _
    id As Integer _
) As SPListItem
Visual Basic (Usage)
Dim instance As SPList
Dim id As Integer
Dim returnValue As SPListItem

returnValue = instance.GetItemById(id)
C#
public SPListItem GetItemById (
    int id
)

Parameters

id

A 32-bit integer that identifies the item. The value of this parameter does not correspond to the index of the item within the collection of items for the list, but to the value of the ID property of the >SPListItem class.

Return Value

An SPListItem object that represents the item.
Example

The following code example uses the GetItemById method to return the fourth item from a list and display specified field values of the item.

This example requires using directives (Imports in Visual Basic) for the Microsoft.SharePoint and Microsoft.SharePoint.Utilities namespaces.

The example assumes the existence of an .aspx page that contains a label control.

Visual Basic
Dim siteCollection As SPSite = SPContext.Current.Site
Try
    Dim list As SPList = siteCollection.AllWebs("Site_Name").Lists("List_Name")
    Dim listItem As SPListItem = list.GetItemById(4)

    Label1.Text += SPEncode.HtmlEncode(listItem("Field1_Name").ToString()) + 
        " -- " + SPEncode.HtmlEncode(listItem("Field2_Name").ToString()) + " -- " + 
        SPEncode.HtmlEncode(listItem("Field3_Name").ToString())
Finally
    siteCollection.Dispose()
End Try
C#
SPSite oSiteCollection = SPContext.Current.Site;
SPList oList = oSiteCollection.AllWebs["Site_Name"].Lists["List_Name"];
SPListItem oListItem = oList.GetItemById(4);

Label1.Text += SPEncode.HtmlEncode(oListItem["Field1_Name"].ToString()) 
    + " -- " + SPEncode.HtmlEncode(oListItem["Field2_Name"].ToString()) 
    + " -- " + 
    SPEncode.HtmlEncode(oListItem["Field3_Name"].ToString());
See Also



Community Content

anonymous coward
Failure indicated by throwing ArgumentException
Throws System.ArgumentException with message "Value does not fall within the expected range." if the id argument does not correspond to the id of an item in the list.

John D Wilson
Deleted Item Throws NullReferenceException
If SPListItem represented by the id argument previously existed but has since been deleted.
Tags : exceptions

Page view tracker