How to sort DropDownList items alphabetically in asp.net

DropDownList items sort alphabetically
This is a very useful tip for ASP.NET DropDownList. By default DropDownList items are exists unsorted. To provide better user experience we need to sort the DropDownList items. It help users to find items easily and faster way.

This example show how can we sort DropDownList list items alphabetically (ascending). This action performs only one time when the page load at first time.

On first page load we create a list of DropDownList list items. Then sorted it alphabetically by items text using LINQ. After that we clear items from DropDownList and populate it again by that sorted items. As a result we get a DropDownList which items are sorted ascending.
dropdownlist-sort-alphabetically.aspx

<%@ Page Language="C#" AutoEventWireup="true"%>    
      
<!DOCTYPE html>
        
<script runat="server">  
    protected void Page_Load(object sender, EventArgs e)  
    {   
        if(!Page.IsPostBack)
        {
            //this line create a generic list data type ListItem
            List<ListItem> list = new List<ListItem>();

            foreach (ListItem li in DropDownList1.Items)
            {
                list.Add(li);
            }

            //sort list items alphabetically/ascending
            List<ListItem> sorted = list.OrderBy(b => b.Text).ToList();

            //empty dropdownlist
            DropDownList1.Items.Clear();
            //repopulate dropdownlist with sorted items.
            foreach (ListItem li in sorted)
            {
                DropDownList1.Items.Add(li);
            }
        }
    }
</script>        
        
<html xmlns="http://www.w3.org/1999/xhtml">        
<head id="Head1" runat="server">        
    <title>asp.net dropdownlist sort alphabetically</title>  
</head>        
<body>        
    <form id="form1" runat="server">        
    <div>        
        <h2 style="color:MidnightBlue; font-style:italic;">        
            asp.net example - dropdownlist sort alphabetically
        </h2>        
        <hr width="550" align="left" color="Gainsboro" />        
        <br /><br />  
        <asp:DropDownList  
            ID="DropDownList1"  
            runat="server"  
            AutoPostBack="true"  
            Width="350"  
            Font-Size="X-Large"  
            CssClass="select"  
            >  
            <asp:ListItem Text="Great White Pelican" Value="1"></asp:ListItem>
            <asp:ListItem Text="Brown Pelican" Value="2"></asp:ListItem>
            <asp:ListItem Text="Australian Pelican" Value="3"></asp:ListItem>
            <asp:ListItem Text="Masked Booby" Value="4"></asp:ListItem>
            <asp:ListItem Text="European Shag" Value="5"></asp:ListItem>
        </asp:DropDownList>  
    </div>        
    </form>        
</body>        
</html>
More asp.net examples