Monday, April 18, 2011

Display form URL of a list item or folder

The below code provides a generic way to form/build URL to the Display form of a list item or folder. This code makes use of the default dispform specified for the list through the property splist.Forms[PAGETYPE.PAGE_DISPLAYFORM].Url.

using (SPSite oSPSite=new SPSite("< site url > "))
            {
                using (SPWeb oSPWeb=oSPSite.OpenWeb())
                {
                    SPList oSPList = oSPWeb.Lists["ListName"];
                    SPListItem oSPListItem = oSPList.GetItemById(item_id);
                    string displayUrl;
                    string webUrl = oSPWeb.Url;
                    try
                    {
                        displayUrl = oSPListItem.ContentType.DisplayFormUrl;
                        if (string.IsNullOrEmpty(displayUrl))
                        {
                            displayUrl = oSPList.Forms[PAGETYPE.PAGE_DISPLAYFORM].Url;
                        }
                    }
                    catch (NullReferenceException)
                    {
                        displayUrl = oSPList.Forms[PAGETYPE.PAGE_DISPLAYFORM].Url;
                    }
                        
                    bool isLayouts = displayUrl.StartsWith("_layouts/", StringComparison.CurrentCultureIgnoreCase);
                    displayUrl = String.Format("{0}/{1}?ID={2}", webUrl, displayUrl, oSPListItem.ID);
                    if (isLayouts)
                        displayUrl = String.Format("{0}&List={1}", displayUrl, SPEncode.UrlEncode(oSPList.ID + ""));

                }
            }

Here, the displayUrl gives the link to the dispform of the item.


No comments: