How to: Read the Value of a Field in a List Item

Applies to: SharePoint Foundation 2010

This topic explains how to programmatically read the value of a specific field (column) in a specific list item.

Overview

To read the value of a specific field in a list item, your code must first get a reference to the Web site on which the list is deployed, then a reference to the list itself, then a reference to the list item, and finally a reference to the specific field. This topic concentrates on the last three steps, especially the very last. For more information about getting references to Web sites, see Getting References to Sites, Web Applications, and Other Key Objects.

Getting a Reference to a List

After you have a reference to the Web site that contains the list, you obtain a reference to the list by either calling the GetList(String) method of the SPWeb object or by using an index of the Web site's SPWeb.Lists property. To use the GetList(String) method your code must be able to pass the server-relative URL of the list at run time. The following shows an example of using this method when the literal server-relative URL of the list is known at design time.

using (SPSite siteCol = new SPSite("https://server/sites/Contoso"))
{
    using (SPWeb web = siteCol.RootWeb)
    {
         SPList list = web.GetList("/sites/Contoso/Lists/Books");
    }
}

For more information about server-relative URLs, see Describing Forms of URL Strings.

There are three types of indexes that you can use with the SPWeb.Lists property.

  • The GUID of the list; for example, SPList list = web.Lists[new Guid("53bd7850-49cc-4747-aded-e053659ace79")];. The GUID is the value of the SPList.ID property.

  • The zero-based ordinal position of the list in the Lists collection; for example SPList list = web.Lists[12];.

  • The name of the list; for example SPList list = web.Lists["Books"];. The name is the value of the SPList.Title property.

The last of these is the most common, because it is relatively rare that you will know at design time, or that your code will "know" at run time, the GUID of the list or its position in the Web site's collection of lists. The following shows this technique in context.

using (SPSite siteCol = new SPSite("https://server/sites/Contoso"))
{
    using (SPWeb web = siteCol.RootWeb)
    {
         SPList list = web.Lists["Books"];
    }
}

Tip

In Microsoft SharePoint Foundation, if a "Get" method is available to return a particular type of object, you should use it in preference to using an index of a collection. In general, you get better performance by following this rule. In this case, if your code can pass the needed server-relative URL of the list at run time, you should use the GetList(String) method in preference to an index of the SPWeb.Lists property.

Getting a Reference to a List Item

After you have a reference to the list, you have several choices for obtaining a reference to a particular list item. For best performance, the preferred choice is to use the GetItemByIdSelectedFields(Int32, []) method of the SPList object. The first parameter is the ID number of the item. Each time an item is added to a list, it is given a 1-based integer ID that is one greater than the ID of the previous item added. When an item is deleted from a list, its ID number is not reused. The second parameter is an array of the internal names of the fields from the item that you want returned from the content database. To maximize performance, include only the fields of the list item that your code will reference later. The following is an example.

using (SPSite siteCol = new SPSite("https://server/sites/Contoso"))
{
    using (SPWeb web = siteCol.RootWeb)
    {
        SPList list = web.GetList("/sites/Contoso/Lists/Books");
        
        SPListItem item = list.GetItemByIdSelectedFields(3, "Title", "ISBN", "Retail_x0020_Price");
    }
}

Note that the list item with ID 3 is being retrieved, but only three of its fields are being retrieved. Note also, that the InternalName of the retail price field is used, not the field's Title property, which in this case is "Retail Price".

If you want all the fields of the list item, use the GetItemByIdAllFields(Int32) method. Its only parameter is the item ID. There are some special purpose methods for getting list items of special types. If you know the item's GUID (the value of its UniqueId property) rather than the value of its ID property, use the GetItemByUniqueId(Guid) method.

If you do not know either the GUID or the ID of the list item, but you know the value some of its other fields or properties, you can use one of the overloads of the GetItems() method to return multiple list items and then use a loop and conditional structures to select the one you want. The following is an example of this technique.

using (SPSite siteCol = new SPSite("https://server/sites/Contoso"))
{
    using (SPWeb web = siteCol.RootWeb)
    {
        SPList list = web.GetList("/sites/Contoso/Lists/Books");
        
        SPListItemCollection items = list.GetItems("Title", "ISBN", "Retail_x0020_Price");
        SPListItem item = null;
        foreach (SPListItem it in items)
        {
            if (it.Title == "Great Expectations")
            {
                 item = it;
            }
        }
}

You can also query a list for a filtered set of items by using the LINQ to SharePoint provider. Use the select clause of your LINQ query to specify just the fields that you want. For more information about querying SharePoint with LINQ, see How to: Query Using LINQ to SharePoint.

Important

The SPList object has an Items property whose members you can access with an index, but we recommend against doing so because this technique causes all the metadata for all the list items to be fetched from the content database.

Getting the Value of a Field

After you have a reference to the list item that you want, your code can read the value of any field by using an index of the SPListItem object. There are Guid, Int32, and String indexes. You can use the Guid index if you know the Id of the field. You can use the Int32 index if you know the zero-based column number of the field in the parent list. You can use the String index if you know the InternalName, the Title, or the StaticName of the field. The runtime searches for the string in internal names first, then field titles, and finally field static names; so your code performs better if you use the internal name when you know it. The following is an example of this technique. Note that the indexer always returns the field value as type Object. You usually need to cast it to its more specific type as is done in this example.

using (SPSite siteCol = new SPSite("https://server/sites/Contoso"))
{
    using (SPWeb web = siteCol.RootWeb)
    {
        SPList list = web.GetList("/sites/Contoso/Lists/Books");
        
        SPListItem item = list.GetItemByIdSelectedFields(3, "Title", "ISBN", "Retail_x0020_Price");

        String bookISBN = (String)item["ISBN"];
    }
}

If you want the field's value formatted for injection into HTML code as either the value of an element or an attribute of an element, use the SPListItem.GetFormattedValue(String) method. It returns the value as a string, but if the value contains any ampersand, double-quotation, single-quotation, less-than, or greater-than characters, they are replaced with the appropriate HTML entity references.

The SPField class itself (and, thus, each class that derives from it) has some methods for converting a field value in special ways. In each of these, you first obtain a reference to the field value by using an index with the SPListItem object as described above. You pass that reference as a parameter to one of these methods; for example, GetFieldValueAsText(item["ISBN"]).

To use any of these methods, you must get a reference to the field as an SPField object. You do this by using the SPListItem.Fields property of the list item. This is a collection of the fields in the parent list. The type is SPFieldCollection. This object, in turn, provides several ways of returning a specified SPField object.

  • Using the GetField(String) method. Pass the internal name, the title, or the static name of the field. Internal name is searched for first, so for better performance use internal name when you know it. Static name is searched for last.

  • Using the GetFieldByInternalName(String) method.

  • Using the TryGetFieldByStaticName(String) method.

  • Using a Guid, Int32, or String index of the SPListItem.Fields property of the list item. The first index returns the SPField object whose Id property matches the Guid object that is passed. The second index returns the SPField object at the specified zero-based ordinal position in the collection. The third index returns the SPField object whose Title property matches the string that is passed. (You cannot use the internal name of the field as the string index.)

The following code shows some examples of how to use the indexes and methods of the SPListItem and SPField-derived classes to get the value of a field.

using (SPSite siteCol = new SPSite("https://server/sites/Contoso"))
{
    using (SPWeb web = siteCol.RootWeb)
    {
        SPList list = web.GetList("/sites/Contoso/Lists/Books");
        
        SPListItem item = list.GetItemByIdSelectedFields(3, "Title", "ISBN", "Retail_x0020_Price");

        // Get price as Double straight from the SPListItem object.
        Double dblPrice = (Double)item["Retail_x0020_Price"];        

        // Get the SPField object by using the GetFieldByInternalName method, and then get
        // price as string. 
        SPFieldCurrency priceField = (SPFieldCurrency)item.Fields.GetFieldByInternalName("Retail_x0020_Price");
        String strPrice = priceField.GetFieldValueAsText(item["Retail_x0020_Price"])

        // Get price as string from the SPField object. Use string SPFieldCollection index 
        // to get the SPField object (must use field object Title as index parameter). But 
        // use internal name of field as SPListItem index for better performance.
          String strPrice2 = item.Fields["Retail Price"].GetFieldValueAsText(item["Retail_x0020_Price"]);
    }
}

See Also

Concepts

How to: Enumerate Sites and Site Collections

How to: Return Items from a List