While programming with SharePoint Object Model, sometimes we are in situation where we need to check if a list is already exists in given scope especially or we should create a new list. We can check this by creating a list in a try block and if list already exists it will throw exception which will be handled in catch block. However we can check it by other couple of ways.
- Check if lists exists.
- Iterate through collection of lists and match for each list with specified list name.
string listName = "Tasks"; SPSite site = (SPSite)properties.Feature.Parent; SPWeb webName = site.RootWeb; bool isListExixts = webName.Lists.TryGetList(listName); if (isListExixts == true) // List Exists. |
string listName = "Tasks"; SPSite site = (SPSite)properties.Feature.Parent; SPWeb webName = site.RootWeb; SPListCollection listCollection = webName.Lists; foreach (SPList tempList in listCollection) { if (tempList.Title == listName) return true; } |
- Iterate through list of collection using this code.
string listName = "Tasks"; SPSite site = (SPSite)properties.Feature.Parent; SPWeb webName = site.RootWeb; if(webName.Lists.Cast<SPList>().Any(list => list.Title.Equals(listName, StringComparison.OrdinalIgnoreCase))) { return true; } |
No comments:
Post a Comment