Implementing a simple Cascading Dropdown in a usercontrol

A user wanted some guidance on how to implement a cascading dropdown in SharePoint. The following will show a simple example of how to implement that as a user control which has properties for selecting a list, a choice field in that list for the first dropdown and a field for which all appropriate values are shown in the second dropdown

When creating the user control you can choose either to do it quick and dirty (only recommended for testing) or as a real solution for deployment to a farm

Quick and dirty:

As a solution:

CascadingDropDown.ascx:

<%@ Control Language="C#" compilationMode="Always" %>
<% @ Assembly Name ="Microsoft.SharePoint, 
              Version=12.0.0.0, 
              Culture=neutral, 
              PublicKeyToken=71e9bce111e9429c" %>
<%@ Import Namespace="Microsoft.SharePoint" %>
<asp:dropdownlist id="main" runat="server" enabled="false" autopostback="true" /%>
<asp:dropdownlist id="sub" runat="server" enabled="false" /%>
<script runat="server"%>
string _List;
public string List
{
    get {return _List;}
    set {_List=value;}
}
string _MainField;
public string MainField
{
    get {return _MainField;}
    set {_MainField=value;}
}
string _SubField;
public string SubField
{
    get {return _SubField;}
    set {_SubField=value;}
}
protected override void OnLoad(EventArgs ea)
{
    if (!IsPostBack)
    {
        SPList list=SPContext.Current.Web.Lists[List];
        SPField mainfield=list.Fields[MainField];
        if (mainfield is SPFieldMultiChoice)
        {
            SPFieldMultiChoice cf = mainfield as SPFieldMultiChoice;
            foreach (string choice in cf.Choices)
                main.Items.Add(new ListItem(choice,choice));
        }
        if (main.Items.Count > 0)
        {
            main.Enabled = true;
            OnMainSelectedIndexChanged(this,ea);
        }
    }
    main.SelectedIndexChanged += OnMainSelectedIndexChanged;
}
protected void OnMainSelectedIndexChanged(object sender, EventArgs ea)
{
    SPList list=SPContext.Current.Web.Lists[List];
    SPQuery query=new SPQuery();
    query.Query=String.Format(
        "<where>"+
            "<eq>"+
                "<fieldref name="\"{0}\"">"+
                "<value type="\"Choice\"">{1}</value>"+
            "</fieldref>"+
        "</eq>",
        MainField,
        main.SelectedValue);
    sub.Items.Clear();
    foreach (SPListItem item in list.GetItems(query))
    {
        sub.Items.Add(item[SubField].ToString());
    }
    sub.Enabled = sub.Items.Count > 0;
}
</script%>

Add a register tag on your page:

<%@ Register TagPrefix="tbks" TagName="cdd" src="~/_controltemplates/theblackknightsings/CascadingDropDown.ascx" %>

Use the control:

<tbks:cdd list="listname" mainfield="Choice field" subfield="other field" runat="server" /> 
comments powered by Disqus