How to sort DropDownListi items alphabetically in asp.net c#
As we know that RadioButtonList and dropdownlist
both items is unsorted by default. But many times we want to sort our DropDownList
items by alphabetically.As In the previous
we will discuss How to sort RadioButtonList items alphabetically in asp.net c# so in this article, we will learn about how to
sort DropDownList items alphabetically in asp.net c#
Source code:-
<%@ Page Language="C#" AutoEventWireup="true" CodeFile="sortlist.aspx.cs" Inherits="sortlist" %>
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title></title>
</head>
<body>
<form id="form1" runat="server">
<div>
<fieldset style="width:400px">
<legend>Unsort
DropDownList items</legend>
<asp:DropDownList ID="drpcity" runat="server" width="400px">
<asp:ListItem>Agra</asp:ListItem>
<asp:ListItem>Lucknow</asp:ListItem>
<asp:ListItem>Delhi</asp:ListItem>
<asp:ListItem>Pune</asp:ListItem>
<asp:ListItem>Mumbai</asp:ListItem>
<asp:ListItem>Goa</asp:ListItem>
<asp:ListItem>Bahraich</asp:ListItem>
<asp:ListItem>Jhansi</asp:ListItem>
</asp:DropDownList>
</fieldset>
</div>
</form>
</body>
</html>
Code behind(c#)
using
System;
using
System.Collections.Generic;
using
System.Linq;
using
System.Web;
using
System.Web.UI;
using
System.Web.UI.WebControls;
public partial class sortlist :
System.Web.UI.Page
{
protected void
Page_Load(object sender, EventArgs e)
{
if
(!Page.IsPostBack)
{
List<ListItem>
list = new List<ListItem>();
foreach (ListItem li in
drpcity.Items)
{
list.Add(li);
}
List<ListItem>
sorted = list.OrderBy(b => b.Text).ToList();
drpcity.Items.Clear();
foreach (ListItem li in
sorted)
{
drpcity.Items.Add(li);
}
}
}
}
Out-put:-
How to sort DropDownListi items alphabetically in asp.net c#
Reviewed by NEERAJ SRIVASTAVA
on
8:21:00 PM
Rating:
No comments: