SharePoint Web Controls to access remote content

SharePoint Web Controls to access remote content

In my post How to use the SharePoint Web Controls I talked about using the SharePoint Web Controls to show and edit data in SharePoint lists.

Today I want to post a sample how to work on a list, which is in another web. The remote list will be the "User Information List" which exists on every rootWeb.

   1:  // connect to the rootweb, to read the users list
   2:  var rootWeb = SPContext.Current.Site.RootWeb;
   3:  {
   4:      // get the current user and corresponding item in the user information list
   5:      SPUser user = SPContext.Current.Web.CurrentUser;
   6:      SPList list = rootWeb.Lists["User Information List"];
   7:      SPListItem userItem = list.GetItemById(user.ID);
   8:   
   9:      // set the context, so the controls will work
  10:      SPContext context = SPContext.GetContext(
  11:          HttpContext.Current, userItem.ID, list.ID, rootWeb);
  12:   
  13:      // Username
  14:      Controls.Add(new Label { Text = "Username:" });
  15:      var username = new TextField
  16:      {
  17:          ID = "Username",
  18:          FieldName = "Title",
  19:          ItemId = userItem.ID,
  20:          ListId = list.ID,
  21:          ControlMode = SPControlMode.Edit,
  22:          RenderContext = context,
  23:          ItemContext = context
  24:      };
  25:      Controls.Add(username);
  26:   
  27:      // about me
  28:      Controls.Add(new Label { Text = "About me:" });
  29:      var aboutMe = new RichTextField
  30:      {
  31:          ID = "AboutMe",
  32:          FieldName = "Notes",
  33:          ItemId = userItem.ID,
  34:          ListId = list.ID,
  35:          ControlMode = SPControlMode.Edit,
  36:          RenderContext = context,
  37:          ItemContext = context
  38:      };
  39:      Controls.Add(aboutMe);
  40:  }

The key point is to create a context, which is different from the current. This new context will be used by the SharePoint Web Controls to render data from the User Information List. The output would be something like this:

If you do not set the context for the controls and try to access data from another context (which you try if you specify the list from another web), you will get an InvalidOperationException.

Operation is not valid due to the current state of the object.

Technorati Tags: ,

1 Comment

dave

Reply

Rene,

Do you know if this is possible without using an itemID.
I am trying to do the above into an empty list but it will not work unless that list has a item – getitembyid.

I am using spcontrol.add instead of edit but it will not work

Any idea?

 

Leave a Reply