Code Snippet: Read All Items in an External List on the Server
Applies to: SharePoint Server 2010
In this article
Description
Prerequisites
To use this example
Description
The following code snippet shows you how to read all items from an external list.
Prerequisites
Microsoft SharePoint Server 2010 or Microsoft SharePoint Foundation 2010 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
Start Visual Studio and create a C# Console application project. Select .NET Framework 3.5 when you create the project.
From the View menu, click Property Pages to bring up the project properties.
In the Build tab, for the Platform target, select as Any CPU.
Close the project properties window.
In Solution Explorer, under References, remove all project references except for System and System.Core.
Add the following references to the project:
Microsoft.SharePoint
System.Web
Replace the autogenerated code in Program.cs with the code listed at the end of this procedure.
Replace the <siteUrl> and <ExternalListName> string values with valid values.
Save the project.
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>"];
foreach (SPListItem item in list.Items)
{
string val;
foreach (SPField fld in item.Fields)
{
if (item[fld.Title] != null)
val = item[fld.Title].ToString();
else
val = "<NULL>";
Console.Write(val + " ");
}
Console.WriteLine();
}
}
}
}
}