SPListItem Class
Represents an item or row in a list.
Inheritance Hierarchy
System.Object
Microsoft.SharePoint.SPSecurableObject
Microsoft.SharePoint.SPItem
Microsoft.SharePoint.SPListItem
Namespace: Microsoft.SharePoint
Assembly: Microsoft.SharePoint (in Microsoft.SharePoint.dll)
Available in Sandboxed Solutions: Yes
Available in SharePoint Online
Syntax
'Declaration
<SubsetCallableTypeAttribute> _
Public Class SPListItem _
Inherits SPItem
'Usage
Dim instance As SPListItem
[SubsetCallableTypeAttribute]
public class SPListItem : SPItem
Remarks
You can use an indexer to return a single item from a list item collection. For example, if the collection is assigned to a variable named collListItems, use collListItems[index] in Microsoft C#, or collListItems(index) in Microsoft Visual Basic, where index is the index number of the item in the collection, or the internal name or display name of a list field. For an indexer based on a name, Microsoft SharePoint Foundation first looks for the field by internal name and then by display name.
Important
To improve performance and optimize the number of SQL Server queries that SharePoint Foundation must execute, use GetItems or another GetItem* method of the SPList class to retrieve items based on the value of their fields. The GetItems method allows you to specify search criteria by passing a Collaborative Application Markup Language (CAML) query through the SPQuery or SPView class. In addition, list performance may be compromised if a list contains an unnecessarily large number of fields. Use the GetItemByIdSelectedFields(Int32, []) method to limit the fields that are retrieved for an item.
To assign values to a field in a list item using an indexer, the values must be represented in a format that is appropriate for each built-in field type. The following table shows how the data types that are used in SharePoint Foundation field types map to Microsoft .NET Framework types.
Name |
Format |
---|---|
Attachments |
System.Boolean |
Boolean |
System.Boolean |
Calculated |
N/A |
Choice |
System.String |
Computed |
N/A |
Counter |
System.Int32 |
CrossProjectLink |
System.Boolean |
Currency |
System.Double |
DateTime |
System.DateTime |
GridChoice |
System.String |
Guid |
System.Guid |
Integer |
System.Int32 |
Lookup |
System.String |
MaxItems |
System.Int32 |
ModStat |
System.Int32 |
MultiChoice |
System.String |
Note |
System.String |
Number |
System.Double |
Recurrence |
System.Boolean |
Text |
System.String |
Threading |
System.String |
URL |
System.String, System.String |
User |
System.String |
Note |
System.String |
Unlike all other members in the object model, the indexer for a DateTime field returns values in local time on the site. In a query, set the DatesInUtc property of the SPQuery object to true for the indexer to return values in Universal Coordinated Time (UTC). If the values are returned in local time and you want to convert them to UTC, use the LocalTimeToUTC method, as follows:
oWebsite.RegionalSettings.TimeZone.LocalTimeToUtc(date)
For more information about the conversion and format of date and time values in SharePoint Foundation, see Converting Date and Time Values.
Using the SPListItem class to modify an event that is linked to a Meeting Workspace site will not update the associated Meeting Workspace site and is not supported.
The type that is returned for the value of a Calculated field depends on the output type of the calculated column.
A Lookup field contains a string in the form ID;#VALUE, where ID is the list item ID and VALUE is the value of the lookup field in the other list. For multivalued lookups, a Lookup field contains a collection.
The value of a MultiChoice field is represented as a string that contains all the selected choices separated by ;#.
The URL field uniquely consists of two strings that are separated by a comma and space. One string contains the URL path and the other contains the description that is used as hyperlinked text.
You can set the value for a User field with an SPUser object, as shown in the following example, which updates an item in the Assigned To field of a tasks list.
Dim site As SPWeb =
SPControl.GetContextSite(Context).AllWebs("Site_Name")
Dim list As SPList = site.Lists("Tasks")
Dim listItem As SPListItem = list.Items(5)
listItem("Assigned To") = site.AllUsers("User_Name")
listItem.Update() '
using(SPWeb oWebsite = SPContext.Current.Site.AllWebs["Site_Name"])
{
SPList oList = oWebsite.Lists["Tasks"];
SPListItem oListItem = oList.Items[5];
oListItem["Assigned To"] = oWebsite.AllUsers["User_Name"];
oListItem.Update();
}
A User field contains a string in the form ID;#User_Display_Name, where ID is the member identifier (ID) of the associated user. The following example parses the value of an Assigned To field to return an SPUser object.
Dim userValue As String = listItem("Assigned To")
Dim index As Integer = userValue.IndexOf(";")
Dim id As Integer = Int32.Parse(userValue.Substring(0, index))
Dim user As SPUser = site.SiteUsers.GetByID(id)
string strUserValue = oList["Assigned To"];
int intIndex = strUserValue.IndexOf(';');
int intID = Int32.Parse(strUserValue.Substring(0, intIndex));
SPUser oUser = oWebsite.SiteUsers.GetByID(intID);
When you are creating a list item, you can set the Author, Editor, Created, and Modified fields the same way that you set other fields of an SPListItem object. The code must be running with site administrator rights in order to function correctly. Set the Author and Editor fields by using the numerical ID of the user, which you can obtain through the object model by using members of SPUser and related classes. The following examples show how to set these fields.
Note that there are no methods or properties for retrieving the metadata for the currently approved version of a list item. (This presumes that you have enabled both versioning and content approval for the list item.) To work around this problem, you can retrieve metadata for the current approved version using the following
using System;
using System.Collections.Generic;
using System.Text;
using Microsoft.SharePoint;
using System.Collections;
namespace GetListItemVersionInformation
{
class Program
{
static void Main(string[] args)
{
SPSite oSite = new SPSite("http://sigr8-1b:1000/sites/MyTestSite");
SPWeb oWeb = oSite.OpenWeb();
SPList oList = oWeb.Lists["MyCustomList"];
SPListItem oListItem = oList.Items.GetItemById(1);
SPListItemVersionCollection oVersionInfo = oListItem.Versions;
int i=0;
foreach (SPListItemVersion oVersion in oVersionInfo)
{
if (oVersion.Level == SPFileLevel.Published)
{
// here we retrieve all metadata properties
// for this item with the current approved version.
// after taking these values we can export them
Console.WriteLine(oListItem.Versions[i]["Address"].ToString());
Console.WriteLine(oListItem.Versions[i]["Title"].ToString());
Console.ReadLine();
return;
// after getting the latest approved version
// we are exiting the code
}
i++;
}
}
}
}
Examples
The following code example uses an indexer to verify the value of a particular field in the specified list. If the value does not equal "None", indexers for two other fields are used to display values from particular fields.
This example requires using directives (Imports in Microsoft Visual Basic) for the Microsoft.SharePoint and Microsoft.SharePoint.Utilities namespaces.
Dim siteCollection As SPSite = SPControl.GetContextSite(Context)
Dim srcList As SPList =
siteCollection.AllWebs("Site_Name").Lists("List_Name")
Dim listItems As SPListItemCollection = srcList.Items
Dim listItem As SPListItem
For Each listItem In listItems
If listItem("Choice_Field_Name") <> "None" Then
Label1.Text += SPEncode.HtmlEncode(listItem("Field1_Name")) & "
:: " _
& SPEncode.HtmlEncode(listItem("Field2_Name")) & "<BR>"
End If
Next listItem
SPSite oSiteCollection = SPContext.Current.Site;
SPList oList =
oSiteCollection.AllWebs["Site_Name"].Lists["List_Name"];
SPListItemCollection collListItems = oList.Items;
foreach (SPListItem oListItem in collListItems)
{
if (oListItem["Choice_Field_Name"] != "None")
{
Label1.Text += SPEncode.HtmlEncode(oListItem["Field1_Name"]) + "
-- " +
SPEncode.HtmlEncode(oListItem["Field2_Name"]) + "<BR>";
}
}
The previous code example assumes the existence of an .aspx page that contains a label control.
The following code example adds an item to an Announcements list, using date and time indexers to assign values to different fields.
Dim site As New SPSite("http://Site_Name")
Dim web As SPWeb = site.OpenWeb("/")
Dim list As SPList = web.Lists("Announcements")
Dim item As SPListItem = list.Items.Add()
item("Title") = "My Item"
item("Created") = New DateTime(2004, 1, 23)
item("Modified") = New DateTime(2005, 10, 1)
item("Author") = 3
item("Editor") = 3
item.Update()
using (SPSite oSiteCollection = new SPSite("http://Site_Name"))
{
using (SPWeb oWebsiteRoot = oSiteCollection.OpenWeb("/"))
{
SPList oList = oWebsiteRoot.Lists["Announcements"];
SPListItem oListItem = oList.Items.Add();
oListItem["Title"] = "My Item";
oListItem["Created"] = new DateTime(2004, 1, 23);
oListItem["Modified"] = new DateTime(2005, 10, 1);
oListItem["Author"] = 3;
oListItem["Editor"] = 3;
oListItem.Update();
}
}
Note
Certain objects implement the IDisposable interface, and you must avoid retaining these objects in memory after they are no longer needed. For information about good coding practices, see Disposing Objects.
Thread Safety
Any public static (Shared in Visual Basic) members of this type are thread safe. Any instance members are not guaranteed to be thread safe.