To better appreciate the intuitiveness and ease of programming with the object model, let’s quickly create a console application that displays all the lists in a top-level SharePoint site under a given site collection.
Try It Yourself: Display Lists in a SharePoint Site
To display lists in a SharePoint site, follow these steps:
1. Fire up Visual Studio, create a new console application, and add a reference to Microsoft.SharePoint.dll assembly. As discussed in Hour 3, “Starting Development with SharePoint 2010,” make sure that your console application targets .NET Framework 3.5 and has either X64 or Any CPU set under the Platform Target property present in the project’s Build configuration tab. By default Visual Studio 2010 sets this value to X86.
2. Next create a DisplayAllLists
function to navigate through all the lists in a site and write their title to the console window, as illustrated in the following code:
public static void DisplayAllLists(string url)
{
using (SPSite siteCollection = new SPSite(url))
{
SPWeb web = siteCollection.RootWeb;
foreach (SPList list in web.Lists)
{
Console.WriteLine(list.Title);
}
}
}
The preceding code starts off by instantiating a new SPSite
object and obtains a reference to its top-level site (or the root web). Then using an SPList
object the code iterates through all the lists in the root web and writes their titles to the console window.
3. Make a call to the DisplayAllLists
function from the Main
function by passing in the URL of a SharePoint site. For complete source code refer to the ListRetrieverApp
project in the source code for this hour.
4. Run the console application either by pressing F5 or clicking the Start Debugging button. This causes all the lists under the top-level SharePoint site of the current site collection to be displayed in the console window.