R100
R100

Reputation: 481

Retrieve List Items from a different Site Collection in SharePoint 2010

I am having issues with retrieving list items from a different site collection. I don't have issues when trying to recieve list items from within my current site collection. For example, http://myintranet.com/Departments/IT works. But http://myintranet.com/sites/Departments/IT returns an error.

if (!String.IsNullOrEmpty(SiteName) && !String.IsNullOrEmpty(SPContext.Current.Web.Url))
    {
      SPSecurity.RunWithElevatedPrivileges(delegate()
      {
        using (SPSite intranetSite = new SPSite(SPContext.Current.Web.Url))
        {
          using (SPWeb currentWeb = intranetSite.AllWebs["/sites/projects/Physics"])
          {
            SPList postList = currentWeb.Lists.TryGetList("Issues");                

            if (postList != null)
            {
              IssueList.DataSource = postList.Items.GetDataTable();

              IssueList.DataBind();
            }
          }
        } 

      });
    }

I haven't used any different code to what I normally do when trying to recieve list items. The only difference is that this time I getting list items from another site collection.

Thanks for any help!

Upvotes: 0

Views: 6619

Answers (1)

James Love
James Love

Reputation: 1020

The problem is intranetSite.AllWebs. This will only get SPWeb objects under your current site collection.

You cannot infer another site collection directly from one site collection.

Even though /sites/projects LOOKS like chid site collection from /, it;s not. /sites is just a managed path. / and /sites/projects are at the same level of the site collection hierarchy.

What you need to do is to this:

if (!String.IsNullOrEmpty(SiteName) && !String.IsNullOrEmpty(SPContext.Current.Web.Url))
    {
      SPSecurity.RunWithElevatedPrivileges(delegate()
      {

          using (SPWeb currentWeb = new SPSite("http://server/sites/projects/Physics").OpenWeb())
          {
            SPList postList = currentWeb.Lists.TryGetList("Issues");                

            if (postList != null)
            {
              IssueList.DataSource = postList.Items.GetDataTable();

              IssueList.DataBind();
            }
          }

      });
    }

Upvotes: 2

Related Questions