How to sort DropDownListi items alphabetically in 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 c#  so in this article, we will learn about how to sort DropDownList items alphabetically in c#

Source code:-

<%@ Page Language="C#" AutoEventWireup="true" CodeFile="sortlist.aspx.cs" Inherits="sortlist" %>

<!DOCTYPE html>

<html xmlns="">
<head runat="server">
    <form id="form1" runat="server">
        <fieldset style="width:400px">
            <legend>Unsort DropDownList items</legend>
            <asp:DropDownList ID="drpcity" runat="server" width="400px">

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<ListItem> sorted = list.OrderBy(b => b.Text).ToList();


            foreach (ListItem li in sorted)

How to sort DropDownListi items alphabetically in c# How to sort DropDownListi items alphabetically in c# Reviewed by NEERAJ SRIVASTAVA on 8:21:00 PM Rating: 5

No comments:

Powered by Blogger.