How to sort ListBox items programmatically in asp.net

The ListBox server control is very similar to the DropDownList, but differs in its display. You can have more than one item at a time shown to the user. The ListBox also enables users to select more than one item at time. For example, if you have a site that delivers news to its users you can allow users to select the type of news they want (for example sports, world) using the ListBox.

Multiple item selection is a behavior over which you have control. By default the ListBox allows users to select only a single item in the list, but by setting the ListBox.SelectionMode attribute to Multiple multiple item selection is enabled. The following lists the two values you can use for the SelectionMode attribute:

  • Single Single item selection (default)
  • Multiple Multiple item selection

asp.net listbox sort items

The following asp.net c# example code demonstrates to us the technique to sort ListBox items programmatically at run time. We sorted the items on the PageLoad event and not in page PostBack stage. We sort the ListBox items the first time the page is loaded.

By default, ListBox server control has no built in functionality to sort its items. To sort ListBox items, first we initialize a Generic List with data type ListItem. Next, we loop through the ListBox items and populate the Generic List with ListBox items. After all we sort the generic list items by its OrderBy() method. In this tutorial, we sorted ListBox items based on ListItem Text property value.

At last we clear the ListBox and repopulate it with Generic List items. Finally, the browser render ListBox with sorted items.

listbox-sort-items.aspx:

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

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

            List<ListItem> sorted = list.OrderBy(x => x.Text).ToList();

            ListBox1.Items.Clear();
            foreach (ListItem li in sorted)
            {
                ListBox1.Items.Add(li);
            }
        }
    }
    protected void ListBox1_SelectedIndexChanged(object sender, EventArgs e)
    {
        Label1.Text = "you selected....<br />";
        Label1.Text += "item: " + ListBox1.SelectedItem.Text;
        Label1.Text += "<br />value: " + ListBox1.SelectedItem.Value;
    }
</script>        
        
<html xmlns="http://www.w3.org/1999/xhtml">        
<head id="Head1" runat="server">        
    <title>asp.net listbox sort items</title>  
</head>        
<body>        
    <form id="form1" runat="server">        
    <div>        
        <h2 style="color:MidnightBlue; font-style:italic;">        
            asp.net example - listbox sort items
        </h2>        
        <hr width="550" align="left" color="Gainsboro" />        
        <asp:Label       
            ID="Label1"       
            runat="server"      
            Text="select an item from ListBox."
            Font-Size="X-Large"
            Width="350"
            >      
        </asp:Label>      
        <br /><br />  
        <asp:ListBox  
            ID="ListBox1"  
            runat="server"  
            AutoPostBack="true"  
            Width="350"  
            Font-Size="X-Large"
            SelectionMode="Single"
            Height="200"  
            OnSelectedIndexChanged="ListBox1_SelectedIndexChanged"
            >  
            <asp:ListItem Text="Green Broadbill" Value="1"></asp:ListItem>
            <asp:ListItem Text="Common Sunbird-asity" Value="2"></asp:ListItem>
            <asp:ListItem Text="African Broadbill" Value="3"></asp:ListItem>
            <asp:ListItem Text="Thrush-like Schiffornis" Value="4"></asp:ListItem>
            <asp:ListItem Text="Red-bellied Pitta" Value="5"></asp:ListItem>
        </asp:ListBox>  
    </div>        
    </form>        
</body>        
</html>

Related Post