Monday, March 22, 2010

How to get display form URL of a list item

using Microsoft.SharePoint;
using Microsoft.SharePoint.Utilities;

SPListItem item = GetItem(); // some code to get a list item
SPList list = item.ParentList;
SPWeb web = list.ParentWeb;

string webUrl = web.Url;
string dispUrl = item.ContentType.DisplayFormUrl;
if(dispUrl == "")
dispUrl = list.Forms[PAGETYPE.PAGE_DISPLAYFORM].Url;
bool isLayouts = dispUrl.StartsWith("_layouts/",StringComparison.CurrentCultureIgnoreCase);
dispUrl = String.Format("{0}/{1}?ID={2}",webUrl,dispUrl,item.ID);
if(isLayouts)
dispUrl = String.Format("{0}&List={1}",dispUrl,SPEncode.UrlEncode(list.ID+""));
As a result, you will get full display form URL of a list item. However, if you want to get just a “clickable” URL, to place in some hyperlink, you don’t need to write so much code. You may create URL by using only an address of a list display form. SharePoint will analyze provided ID of an item then and redirect your request to appropriate page. You may code just:

SPListItem item = GetItem(); // some code to get a list item
SPList list = item.ParentList;
SPWeb web = list.ParentWeb;
string webUrl = web.Url;
string dispUrl = list.Forms[PAGETYPE.PAGE_DISPLAYFORM].Url;;
dispUrl = String.Format("{0}/{1}?ID={2}",webUrl,dispUrl,item.ID);