Export (0) Print
Expand All
1 out of 3 rated this helpful - Rate this topic

SPListItem class

Represents an item or row in a list.

Namespace:  Microsoft.SharePoint
Assembly:  Microsoft.SharePoint (in Microsoft.SharePoint.dll)
[SubsetCallableTypeAttribute]
public class SPListItem : SPItem

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 noteImportant

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.

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.

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++;
         }
      }
   }
}

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.

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.

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();
    }
}
NoteNote

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.

Any public static (Shared in Visual Basic) members of this type are thread safe. Any instance members are not guaranteed to be thread safe.
Did you find this helpful?
(1500 characters remaining)
Thank you for your feedback

Community Additions

ADD
Show:
© 2014 Microsoft. All rights reserved.