Sort Items in an ASP.NET DropDownList using LINQ

Have you been looking out for a way to sort the items of an ASP.NET DropDownList using LINQ? Here’s a LINQ solution:

<html xmlns="http://www.w3.org/1999/xhtml">
<
head runat="server">
<
title>Sorting DropDownList Items</title>
</
head>
<
body>
<
form id="form1" runat="server">
<
div>
<
asp:DropDownList ID="DropDownList1" runat="server">
<
asp:ListItem Text="Item3"></asp:ListItem>
<
asp:ListItem Text="Item1"></asp:ListItem>
<
asp:ListItem Text="Item4"></asp:ListItem>
<
asp:ListItem Text="Item5"></asp:ListItem>
<
asp:ListItem Text="Item2"></asp:ListItem>
</
asp:DropDownList>
<
br />
<
asp:Button ID="btnSort" runat="server" Text="Sort"
onclick="btnSort_Click"/>
</
div>
</
form>
</
body>
</
html>



C#

protected void btnSort_Click(object sender, EventArgs e)
{
List<string> listItems =
DropDownList1.Items.Cast<ListItem>().Select(item => item.Text).ToList();
listItems.Sort((a, b) => string.Compare(a, b));
DropDownList1.DataSource = listItems;
DropDownList1.DataBind();
}

VB.NET

Protected Sub btnSort_Click(ByVal sender As Object, ByVal e As EventArgs)
Dim listItems As List(Of String) = _
DDL.Items.Cast(Of ListItem)().Select(Function(item) item.Text).ToList()
listItems.Sort(Function(a, b) String.Compare(a, b))
DDL.DataSource = listItems
DDL.DataBind()
End Sub

Before Sorting

image

After Sorting

image






About The Author

Suprotim Agarwal
Suprotim Agarwal, Developer Technologies MVP (Microsoft Most Valuable Professional) is the founder and contributor for DevCurry, DotNetCurry and SQLServerCurry. He is the Chief Editor of a Developer Magazine called DNC Magazine. He has also authored two Books - 51 Recipes using jQuery with ASP.NET Controls. and The Absolutely Awesome jQuery CookBook.

Follow him on twitter @suprotimagarwal.

4 comments:

Anonymous said...

great stuff. Thanks for sharing.
http://taphop.net
http://tatca.vn

Raunak Jhawar said...

Thank you very much

Anonymous said...

This idea works except that it destroys any value items that was part of the list.

Unknown said...

Does anyone have a solution for losing the values portion of the list items?