Take the 2-minute tour ×
SharePoint Stack Exchange is a question and answer site for SharePoint enthusiasts. It's 100% free, no registration required.

I am trying to get a list of items that are contained inside a sharepoint list. When I use the code below I get an error

[ArgumentException: Value does not fall within the expected range.] Microsoft.SharePoint.SPListCollection.GetListByName(String strListName, Boolean bThrowException) ...

The structure is MainSite>Subweb>Subweb>Subweb>List

Am I calling this wrong since it is inside of 3 subwebs?

            using (SPSite site = new SPSite(SPContext.Current.Site.Url.ToString()))
                    using (SPWeb oWebsiteRoot = site.OpenWeb())
                    {
                        SPList oList = oWebsiteRoot.Lists["SInfo"];
                        SPListItemCollection items = oList.Items;

                        foreach (SPListItem listitem in items)
                        {
                            Response.Write(SPEncode.HtmlEncode(listitem["SName"].ToString()) + "<BR>");
                        }
                    }
share|improve this question

2 Answers 2

up vote 1 down vote accepted

Calling new SPSite(SPContext.Current.Site.Url.ToString()) and then calling OpenWeb will open the Root Web of the Site Collection, instead of your subweb. Thus, when you try to get that List it can't find it, giving that error message.

Try new SPSite(SPContext.Current.Web.Url) instead, this opens up the SPSite pointing to your current subweb, and then the call to OpenWeb() will open up the subweb (because the url passed in points to the subweb).

share|improve this answer

I think a simpler way of doing this would be just using the SPContext.Current.Web object instead of creating new SPWeb and SPSite objects.

                    SPListItemCollection items = SPContext.Current.Web.Lists["SInfo"].Items;

                    foreach (SPListItem listitem in items)
                    {
                        Response.Write(SPEncode.HtmlEncode(listitem["SName"].ToString()) + "<BR>");
                    }
share|improve this answer
    
Agreed, unless this block is inside an SPElevatedPrivileges call. –  James Love Aug 9 '11 at 19:38

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.