A Practical Guide to SharePoint 2013

A Practical Guide to SharePoint 2013
A Practical Guide to SharePoint 2013 - Book by Saifullah Shafiq

Tuesday, October 16, 2007

SPWeb fails to return the list

When working on large applications, we usually make mistakes and then spend time debugging the errors that occur because of the mistakes that we make during programming but there are some errors that occur even if you don't make any mistake. Have a look at the following code:
SPWeb web = Site.OpenWeb(SPContext.Current.Web.ID); string strList = SPContext.Current.Web.Url.Substring( .... substring processing ....);
SPList list = web.Lists[strList]; //This line gives error!
Do you see any problem with this code? I didn't notice any thing. It gave me the following error:
Value does not fall within the expected range.<BR/>Source: Microsoft.SharePoint<BR/>Stack trace: at Microsoft.SharePoint.SPListCollection.GetListByName(String strListName, Boolean bThrowException)
at Microsoft.SharePoint.SPListCollection.get_Item(String strListName)
The reason of the error turned out to be the list name. The list name had parentheses which resulted in the error. In small companies, you are the all in all when working on a project but in big companies or when working on large projects, there are several people involved in the project. The list was created by the SharePoint admin and I was getting the list name programmatically. I didn't know the list name had parentheses in it. When you load such a list in browser, SharePoint automatically removes parentheses from the list name and the list works fine but when you try to access the same list programmatically, SharePoint gives you an error. As you will notice, in the code above, I am extracting the list name from "SPContext.Current.Web.Url" and it returns the list name without parentheses in it while the actual list name has parentheses and hence you get an error. Even if you add parentheses to the list name (in your code), you still get an error but a different one. It's a SPException error and returns following message:
Action can not be completed.
Conclusion: Do not use parentheses in list name.

No comments:

Post a Comment