Sitecore offers various methods for accessing items in the sitecore tree. The following shows some examples:
1 2 3 4 5 6 7 8 9 10 11 |
//access item by specific id Item itemByGuid = Sitecore.Context.Database.GetItem(new ID("{5071E33C-C56D-4D8F-9BBB-88DADA911DA5}")); //access item by sitecore path Item itemByPath = Sitecore.Context.Database.GetItem("/sitecore/Content/home/news/article"); //access item by specific id in specific language Item itemByGuidInLanguage = Sitecore.Context.Database.GetItem(new ID("{5071E33C-C56D-4D8F-9BBB-88DADA911DA5}"), LanguageManager.GetLanguage("fr-fr")); //access item by sitecore path in specific language Item itemByPathInLanguage = Sitecore.Context.Database.GetItem(new ID("/sitecore/Content/home/news/article"), LanguageManager.GetLanguage("fr-fr")); |
Typically we will store key item guids and key template guids in static classes so they can be used throughout the code.
From experience it is rare to use path to access items since an items path can change over time – essentially it is content rather than something fixed. An items guid should never change even when it is packaged up and distributed to multiple environments.
Its worth noting that once you have accessed an item, it may be it is null. Another scenario is that it doesnt have any versions – this can be caused by an item being published when it isnt in a final workflow state.
These are easy things to check:
1 2 3 4 5 |
//check the item actually exists if (itemByGuid != null && itemByGuid.Versions.Count > 0) { } |