Condividi tramite


Code Snippet: Update an Item in an External List on the Server

Applies to: SharePoint Server 2010

In this article
Description
Prerequisites
To use this example

Description

You use the Update method of the SPList class to update an item in an external list. The following code snippet shows you how to update an item to an external list.

Prerequisites

  • Microsoft SharePoint Server 2010 or on the server.

  • Microsoft Visual Studio.

  • At least one external content type registered in the BDC Metadata Store and an external list based on the external content type.

    Note

    The external list used in this example cannot use Passthrough authentication.

To use this example

  1. Start Visual Studio and create a new C# Console application project. Select .NET Framework 3.5 when you create the project.

  2. From the View menu, click Property Pages to bring up the project properties.

  3. In the Build tab, for the Platform target, select Any CPU.

  4. Close the project properties window.

  5. In Solution Explorer, under References, remove all project references except for System and System.Core.

  6. Add the following references to the project:

    1. Microsoft.SharePoint

    2. System.Web

  7. Replace the autogenerated code in Program.cs with the code listed at the end of this procedure.

  8. Replace the <siteUrl>, <ExternalListName>, <BdcIdentity> and <Field>, <Value> pairs with valid values.

  9. Save the project.

  10. Compile and run the project.

using System;
using System.Web;
using Microsoft.SharePoint;

namespace Microsoft.SDK.SharePoint.Samples.Bdc.ExternalList
{
    class Program
    {
        static void Main(string[] args)
        {
            using(SPSite site = new SPSite("<siteUrl>"))
            {
                SPServiceContext context = SPServiceContext.GetContext(site);
                SPServiceContextScope contextScope = new SPServiceContextScope(context);

                SPWeb web = site.OpenWeb();
                SPList list = web.Lists["<ExternalListName>"];
                SPListItem item = GetItemByBdcId(list, "<BdcIdentity>");
                item["<Field1>"] = "<Value1>";
                item["<Field2"] = "<Value2>";
                item["<Field3>"] = "<Value3>";
                // Set all fields.
                item.Update();
             }
        }
      public static SPListItem GetItemByBdcId (SPList list, string bdcIdentity)
      {
             SPListItem myitem = null;
          foreach(SPListItem item in list.Items)
          {
              if (item["BdcIdentity"].ToString() == bdcIdentity)
              {
                  myitem = item;
              }
          }
          return myitem;
      }

    }
}

See Also

Concepts

Setting the Context for Using the BDC Object Models