C#, Programming, SharePoint, Web

Convert A Links List To A DropDownList By A Web Part In SharePoint 2013 (C#)

So I have been enjoying the benefit of Mike Smith’s article for a while now (http://techtrainingnotes.blogspot.com/2010/12/sharepoint-convert-links-list-to.html). A client I did a project for was wanting to carry this functionality forward to 2013. The problem: this method didn’t work in 2013.

So I took a programmatic approach to lose the JavaScript dependency. It also will sort the dropdown names by what you type as the description by using the sortedlist in the code behind. It’s fairly simple, here’s what I did:

  • Created a links list and populated some URLs and Descriptions (!!! You need both for below to work, otherwise remove the description dependency in my code !!!)
  • Create a SharePoint 2013 Visual Web Part project
  • Add the dropdownlist control to the control

In the .ascx control I have:

<asp:DropDownList ID="linkDropDown" runat="server" Font-Names="Arial" Font-Size="10pt"
Width="300px" OnSelectedIndexChanged="linkDropDown_SelectedIndexChanged" AutoPostBack="true" EnableViewState="true">
<asp:ListItem Text="Link to ..." Value="#"></asp:ListItem>
</asp:DropDownList>
  • Add the code to the code behind of the control

Now the code behind, here’s my using statements:

using System;
using System.ComponentModel;
using System.Web.UI.WebControls.WebParts;
using Microsoft.SharePoint;
using System.Collections;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;

and here is what I have in the Page_Load and the SelectedIndexChanged event

protected void linkDropDown_SelectedIndexChanged(object sender, EventArgs e)
{
Context.Response.Redirect(linkDropDown.SelectedValue.ToString());
}

protected void Page_Load(object sender, EventArgs e)
{
SortedList sortedLists = new SortedList();

using (SPSite siteCol = new SPSite("http://mysharepoint2013site/"))
{
using (SPWeb web = siteCol.RootWeb)
{
SPList list = web.GetList("/Lists/NameOfLinksList");
SPListItemCollection items = list.GetItems();

foreach (SPListItem it in items)
{
SPFieldUrlValue fieldValue = new SPFieldUrlValue(it["URL"].ToString());
string description = fieldValue.Description;
string url = fieldValue.Url;
sortedLists.Add(description, url);
}
}

IDictionaryEnumerator enumerator = sortedLists.GetEnumerator();
while (enumerator.MoveNext())
{
ListItem listitem = new ListItem();
listitem.Text = enumerator.Key.ToString();
listitem.Value = enumerator.Value.ToString();
linkDropDown.Items.Add(new ListItem(listitem.Text.ToString(), listitem.Value.ToString()));
}
}

Deploy and enjoy!