How to sort DropDownList items in descending order in asp.net


DropDownList items sort order by descending



DropDownList is an asp.net list web server control that allow us to select one item at a time
from a drop-down-list. by default dropdownlist items are not sorted. to provide better user experience, web
developer wants to create a sorted dropdownlist. the following asp.net c# example code demonstrate us how can
we render a dropdownlist server control which items are descending sorted.






DropDownList server control have no built in property or method to sort its items descending or ascending order. we need to
apply few techniques to display a sorted dropdownlist programmatically.






At first we create a generic list which data type is ListItem. now we populate the generic list from dropdownlist
items collection. next we sort the list by descending order using Linq OrderByDescending() extension method. finally we clear the
dropdownlist items, and repopulate the dropdownlist with the sorted generic list. now we can display a descending sorted
dropdownlist on web browser. sorting applied for first page load time only, because we track the postback using page IsPostBack property.




dropdownlist-sort-order-by-descending.aspx



<%@ Page Language="C#" AutoEventWireup="true"%>

<!DOCTYPE html>

<script runat="server">
protected void Page_Load(object sender, EventArgs e)
{
if(!Page.IsPostBack)
{
//create a generic list data type ListItem
List<ListItem> list = new List<ListItem>();

foreach (ListItem litem in DropDownList1.Items)
{
//add ListItem to generic list
list.Add(litem);
}

//sort list items by item text descending
List<ListItem> sorted = list.OrderByDescending(b => b.Text).ToList();

//clear dropdownlist items
DropDownList1.Items.Clear();

//repopulate dropdownlist with sorted items.
foreach (ListItem litem in sorted)
{
DropDownList1.Items.Add(litem);
}
}
}
</script>

<html xmlns="http://www.w3.org/1999/xhtml">
<head id="Head1" runat="server">
<title>asp.net c# dropdownlist sort order by descending</title>
</head>
<body>
<form id="form1" runat="server">
<div>
<h2 style="color:MidnightBlue; font-style:italic;">
asp.net c# example - dropdownlist sort order by descending
</h2>
<hr width="550" align="left" color="Gainsboro" />
<br /><br />
<asp:DropDownList
ID="DropDownList1"
runat="server"
AutoPostBack="true"
Width="350"
Font-Size="X-Large"
Font-Names="Comic Sans MS"
>
<asp:ListItem Text="Grey Goshawk" Value="1"></asp:ListItem>
<asp:ListItem Text="African Harrier Hawk" Value="2"></asp:ListItem>
<asp:ListItem Text="Northern Goshawk" Value="3"></asp:ListItem>
<asp:ListItem Text="Common Black Hawk" Value="4"></asp:ListItem>
<asp:ListItem Text="Philippine Eagle" Value="5"></asp:ListItem>
</asp:DropDownList>
</div>
</form>
</body>
</html>