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

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

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: ,