I had a requirement recently to display the fields of a SharePoint item in another SharePoint site. Now, you can do this with things like the Content Query Web Part, or Data View Web Part, but I was doing a few other things, and specifically, I needed to pull the fields to display from a particular View on the list.
This turned out to be quite an interesting problem. All fields use a subclass of BaseFieldControl, and this is what renders the field – so it appeared to be fairly straight forward. As always, though, there was a little kink to it – you need an SPContext for the site the item comes from, and you need to use this as the contexts for the SPField‘s rendering control:
SPContext ctx = SPContext.GetContext(HttpContext.Current, item.ID, relatedList.ID, relatedWeb);
SPView relatedView = list.DefaultView;
foreach (string vf in relatedView.ViewFields)
{
SPField fld = relatedList.Fields.GetFieldByInternalName(vf);
HtmlGenericControl titleLabel = new HtmlGenericControl("H3");
titleLabel.InnerText = fld.Title;
this.Controls.Add( titleLabel );
BaseFieldControl ctl = fld.FieldRenderingControl;
ctl.ControlMode = SPControlMode.Display;
ctl.ListId = relatedList.ID;
ctl.ItemId = item.ID;
ctl.RenderContext = ctx;
ctl.ItemContext = ctx;
ctl.FieldName = fld.Title;
ctl.ID = Guid.NewGuid().ToString();
this.Controls.Add( ctl );
}
Groovy!