public class SortableDropDownList : DropDownList{
/// /// Binds a collection of objects to the DropDownList. Automatically calls DataBind() /// /// Bound to DataSource /// Bound to DataTextField /// Bound to DataValueField /// Used to supply the initial option such as "-- Select --" (Optional) public void BindDataSource(ICollection dataSource, string dataTextField, string dataValueField, ListItem toolTip) { DataSource = dataSource;
DataTextField = dataTextField;
DataValueField = dataValueField;
DataBind();
if (toolTipListItem != null) {
Items.Insert(0, toolTip);
firstItemIsToolTip = true;
}
}
///
/// Sorts the dropdown list by its text value. The ToolTip list item /// will not be included in the sort if it was provided.
/// public void SortByText() { if (Items.Count > 0) { int indexToStartSorting = 0; int countOfItemsToSort = Items.Count; if (firstItemIsToolTip) {
indexToStartSorting++;
countOfItemsToSort--;
}
ArrayList sortedListItems = new ArrayList(Items);
sortedListItems.Sort(indexToStartSorting, countOfItemsToSort, new ListItemComparer());
Items.Clear();
Items.AddRange((ListItem[]) sortedListItems.ToArray(typeof(ListItem)));
}
}
private class ListItemComparer : IComparer {
public int Compare(object listItem1, object listItem2) {
return ((ListItem)listItem1).Text.CompareTo(((ListItem)listItem2).Text);
}
}
private bool firstItemIsToolTip = false;
protected override void RenderContents(HtmlTextWriter writer) {
base.RenderContents(writer);
}
}
Listed below are the unit tests for verifying functionality:
[
TestFixture]public class SortableDropDownListTests { [
Test] public void TestSortByTextWithoutTooltip() { SortableDropDownList dropDownList = new SortableDropDownList(); dropDownList.BindDataSource(GetRandomItems(),
"Name", "ID", null); dropDownList.SortByText();
Assert.AreEqual("Cat", dropDownList.Items[0].Text);
Assert.AreEqual("Dog", dropDownList.Items[1].Text);
Assert.AreEqual("Zebra", dropDownList.Items[2].Text);
}
[Test]
public void TestSortByTextWithToolTip() {
SortableDropDownList dropDownList = new SortableDropDownList();
dropDownList.BindDataSource(GetRandomItems(), "Name", "ID", new ListItem("-- Select --"));
dropDownList.SortByText();
Assert.AreEqual("-- Select --", dropDownList.Items[0].Text);
Assert.AreEqual("Cat", dropDownList.Items[1].Text);
Assert.AreEqual("Dog", dropDownList.Items[2].Text);
Assert.AreEqual("Zebra", dropDownList.Items[3].Text);
}
private RandomItem[] GetRandomItems() {
RandomItem item1 = new RandomItem(1, "Cat");
RandomItem item2 = new RandomItem(2, "Zebra");
RandomItem item3 = new RandomItem(3, "Dog");
return new RandomItem[] { item1, item2, item3 };
}
private class RandomItem { public RandomItem(int id, string name) { this.id = id; this.name = name; }
public int ID {
get { return id; } }
public string Name {
get { return name; } }
private int id;
private string name;
}
}