July 19, 2009

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



'Like' us on our FaceBook page if you find this blog useful. Thanks!


Did you like this post?
kick it on DotNetKicks.com Save on Delicious
subscribe via rss subscribe via e-mail
print this post follow me on twitter


About The Author

Suprotim Agarwal, ASP.NET Architecture MVP works as an Architect Consultant and provides consultancy on how to design and develop Web applications.

Suprotim is also the founder and primary contributor to DevCurry, DotNetCurry and SQLServerCurry. He has also written an EBook 51 Recipes using jQuery with ASP.NET Controls.

Follow him on twitter @suprotimagarwal

comments

2 Responses to "Sort Items in an ASP.NET DropDownList using LINQ"
  1. Taphop said...
    September 23, 2009 12:43 AM

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

  2. Raunak said...
    January 5, 2010 5:00 AM

    Thank you very much

 

Copyright © 2009-2012 All Rights Reserved for DevCurry.com by Suprotim Agarwal | Terms and Conditions