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
After Sorting
Tweet
4 comments:
great stuff. Thanks for sharing.
http://taphop.net
http://tatca.vn
Thank you very much
This idea works except that it destroys any value items that was part of the list.
Does anyone have a solution for losing the values portion of the list items?
Post a Comment