0

Hello I have this code that goes through the SharePoint site and it looks at all the lists, and returns then to a label. Basically I want it to only grab the current site lists only, and not any subsites under right now I have my SP site like this:

Main Site
-Documents
-Images
-MyListA
--Engineering (subSite)
---Documents
---Images
---MyList10

It duplicates Images Documents the normal lists and MyList10 shows up. All I want is Documents Images and MyListA Thank You

        string webUrl = SPContext.Current.Site.Url.ToString();

        using (SPWeb oWebsite = new SPSite(webUrl).OpenWeb())
        {
            SPWebCollection subSites = oWebsite.Webs;

            foreach (SPWeb subSite in subSites)
            {

                SPListCollection collList = subSite.Lists;

                foreach (SPList oList in collList)
                {
                    Label1.Text = SPEncode.HtmlEncode(oList.Title);
                }

                subSite.Close();
            }
        }
atrljoe
  • 8,031
  • 11
  • 67
  • 110

1 Answers1

2

All you need is this:

    foreach (SPList list in SPContext.Current.Web.Lists)
    {
       Label1.Text = SPEncode.HtmlEncode(list.Title); // notice that it will overwrite label text every time
    }

Also mention, that code you provided have some memory leaks.

EvgK
  • 1,907
  • 12
  • 10
  • For the memory leak are you referring to the fact that I need to dispose it? – atrljoe Feb 07 '11 at 17:00
  • 1
    In code I wrote before nothing should be disposed. In your code you should dispose new SPSite(webUrl) (better use SPContext.Current.Site which should not be disposed). Also, you should better do that: try {...} finally {if (subSite!=null) subSite.Dispose()} instead of simply dispose subSite, because if you get an exception, subSite object will not be disposed. – EvgK Feb 07 '11 at 17:13
  • Thanks, one other question SPContext.Current.Web.Lists returns a lot of system lists, is there anyway to just return fewer items like Documents, Images, and like user created ones. – atrljoe Feb 07 '11 at 17:19
  • 1
    You should anyway enumerate through them all (even if you will use LINQ), but you can filter out system lists: if (!list.Hidden) ...do stuff here... – EvgK Feb 07 '11 at 17:24
  • No a "using" should always close the connection even on an exception. Try is generally disencouraged for this reason that you need a catch and a finally to guarentee that you dont have memory leaks. Reference: http://stackoverflow.com/questions/4717789/in-a-using-block-is-a-sqlconnection-closed-on-return-or-exception – JPK Feb 27 '14 at 13:46