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.