Code Snippet for SharePoint Links List Query Web Part
Recently, I had to “throw together” a quick web part (this is SharePoint 2007) that queries a links list (located on another site) and returns the associated items as a bulleted list. The goal was to use this web part in a site definition so all sites created would have a dynamic reference to hyperlinks managed in a single source. I thought it might be helpful to share the code (nothing overly complex here). Two things of note: (1) SharePoint stores the description and hyperlink for a URL in a single field. It provides an object to help you parse these (so you don’t have to write the extra code). (2) We included a custom sort column to control how the items are presented. There is some extra code below to show how I did that.
My next task is to create a version of this where the list referenced is on another SharePoint server. I’ll use the SharePoint web services to get the list information. I’ll share that snippet when done. Happy coding!
public class SharePointTips : System.Web.UI.WebControls.WebParts.WebPart
{
public SharePointTips()
{
this.ExportMode = WebPartExportMode.All;
}
public class SharePointTip
{
public int sortOrder;
public string tipLink;
public SharePointTip(int sortOrder, string tipLink)
{
this.sortOrder = sortOrder;
this.tipLink = tipLink;
}
}
protected override void Render(HtmlTextWriter writer)
{
string SharePointTipsListSite = System.Configuration.ConfigurationManager.AppSettings["SharePointTipsSite"].ToString();
string SharePointTipsListName = System.Configuration.ConfigurationManager.AppSettings["SharePointTipsList"].ToString();
try
{
using (SPSite site = new SPSite(SharePointTipsListSite))
{
using (SPWeb web = site.OpenWeb())
{
SPList list = web.Lists[SharePointTipsListName];
SPListItemCollection itemCollection;
itemCollection = list.Items;
List<SharePointTip> SharePointTips = new List<SharePointTip>();
foreach (SPListItem item in itemCollection)
{
SPFieldUrlValue listField = new SPFieldUrlValue(item["URL"].ToString());
SharePointTips.Add(new SharePointTip(System.Convert.ToInt32(item["SortOrder"]), "<img src='/_layouts/images/square.gif'> <a href='" + listField.Url + "'>" + listField.Description + "</a><br>"));
}
SharePointTips.Sort(delegate(SharePointTip p1, SharePointTip p2) { return p1.tipLink.CompareTo(p2.tipLink); });
SharePointTips.ForEach(delegate(SharePointTip tip) { writer.Write(tip.tipLink); });
}
}
}
catch (Exception e)
{
writer.Write(e.Message);
}
}