SharePoint 2010 Get SP List programmatically with C#

There are some different ways to access a list in SharePoint 2010 by code. You can look at these SPWeb members in this msdn article. But i’d like to provide you two different ways here to get your list with c#.

In both cases you have to define your web:

SPWeb myWeb = SPContext.Current.Web;

1) Get list by Display Name

SPList myList = web.Lists[“ListDisplayName”];

This option has to be taken carefully, cause what happens if the lovely enduser changes the title of the list? It will change the displayname of the list and your code will not find the list, right?

So i prefer option 2 which gets the list by url. The url does not change even if the enduser gives the list a curios name and is happy with the name.

So how to get this by url?

2) Get list by URL

SPList myList = myWeb.GetList(SPUrlUtility.CombineUrl(myWeb.ServerRelativeUrl, “/Lists/ListUrlName”);

With this line, it doesn’t matter what list title you choose or display name the list had and will have in future, you don’t have to update code cause you updated your listname!

In this blogpost you’ll find some more helpful words.

..:: I LIKE SHAREPOINT ::..

 

The article or information provided here represents completely my own personal view & thought. It is recommended to test the content or scripts of the site in the lab, before making use in the production environment & use it completely at your own risk. The articles, scripts, suggestions or tricks published on the site are provided AS-IS with no warranties or guarantees and confers no rights.

About Karsten Schneider 312 Articles
Consultant for Microsoft 365 Applications with a strong focus in Teams, SharePoint Online, OneDrive for Business as well as PowerPlatform with PowerApps, Flow and PowerBI. I provide Workshops for Governance & Security in Office 365 and Development of Solutions in the area of Collaboration and Teamwork based on Microsoft 365 and Azure Cloud Solutions. In his free time he tries to collect tipps and worthy experience in this blog.

1 Comment

  1. In document library I have a document which is followed by a version history, which has 6 versions, I want to compare difference between 1st version and 2nd version in a report. Thank you for your help.

Leave a Reply

Your email address will not be published.


*