Click here to Skip to main content
Licence CPOL
First Posted 8 Aug 2010
Views 13,498
Bookmarked 6 times

How to sort ASP.NET DropDownList based on DataValueField or DataTextField using LINQ?

By | 8 Aug 2010 | Technical Blog
Sorting ASP.NET Dropdown list is very common requirement for any of the web application development.  To Implement this features sometimes developers used to iterate through each and every item and create a sorted list of element then reassign the same source to dropdownlist or sort the element at s
A Technical Blog article. View original blog here.[^]

Sorting ASP.NET Dropdown list is very common requirement for any of the web application development.  To Implement this features sometimes developers used to iterate through each and every item and create a sorted list of element then reassign the same source to dropdownlist or sort the element at source itself. But this thing can be done easily using LINQ. In this post I am going describe how you can sort a ASP.NET DropDownList based on either of DataTextField or DataValueField using LINQ and list of KeyValuePair elements as DataSource.

To start with the application, let’s consider you have following List of employee data as datasource of the DropDownList.

 /// <summary>
 /// Create List Of Employee
 /// </summary>
 List<KeyValuePair<int, string>> employees = new List<KeyValuePair<int, string>>
        {        new KeyValuePair<int,string>(1,"Abhijit"),
                  new KeyValuePair<int,string>(2,"Rahul"),
                  new KeyValuePair<int,string>(3,"Kunal"),
                  new KeyValuePair<int,string>(4,"Atul"),
                 new KeyValuePair<int,string>(5,"Abhishek"),
        };
 

In the employee list collection, you have added KeyValuePair for each element, where Key is employee ID and Value is the employee name.  The most interesting part of using KeyValuePair is you can bind either of Key or Value with the DropDownList as per your requirement

Now let’s bind the DropDownList with the DataSource

   /// <summary>
    /// Binds the drop down list.
    /// </summary>
    private void BindDropDownList()
    {
        dropDownListEmployee.DataSource = this.employees;
        dropDownListEmployee.DataTextField = "Value";
        dropDownListEmployee.DataValueField = "Key";
        dropDownListEmployee.DataBind();
    }
  

If you call the BindDropDownList(), you will get output like below

Defult

If you look at the code for  BindDropDownList() method we have set the  Value ( Name ) with the DataTextField and Key (ID) with DataValueField, Where Value and Key are the Item of KeyValuePair .

Now, If you want to sort the List Item based on the Name of employee you have used the below code.

   /// <summary>
    /// Binds the drop down list.
    /// </summary>
    private void BindDropDownList()
    {
        dropDownListEmployee.DataSource = this.employees.OrderBy(item => item.Value);
        dropDownListEmployee.DataTextField = "Value";
        dropDownListEmployee.DataValueField = "Key";
        dropDownListEmployee.DataBind();
    }
  

In the above code we are applying sort based on Value of KeyValuePair( Name ).  Below is the sample output for the same.

SortedValue

This is really interesting , where you have just made a single line of change and you got the sorted elements in dropdown list. Here is the most important part, In the above code we have sorted the element based on the DataTextField (Name) now if you want to sort the list based on DataValueField (ID) you just need to use sort based on the Key field. Below is the sample code snippet for the same.

   /// <summary>
    /// Binds the drop down list.
    /// </summary>
    private void BindDropDownList()
    {
        dropDownListEmployee.DataSource = this.employees.OrderBy(item => item.Key);
        dropDownListEmployee.DataTextField = "Value";
        dropDownListEmployee.DataValueField = "Key";<
        dropDownListEmployee.DataBind();
    }

After running the application you will find the dropdown list items as below.

SortKey

Similarly you can also do the Descending  order using Below code snippet

   /// <summary>
    /// Binds the drop down list.
    /// </summary>
    private void BindDropDownList()
    {
      dropDownListEmployee.DataSource = this.employees.OrderByDescending(item => item.Key);
        dropDownListEmployee.DataTextField = "Value";
        dropDownListEmployee.DataValueField = "Key";
        dropDownListEmployee.DataBind();
    }

Below is complete code coverage for the above Demonstration.

using System;
using System.Collections.Generic;
using System.Linq
/// <summary><
/// Default Page Class for Dropdown Sort application Demo
/// </summary>
public partial class _Default : System.Web.UI.Page
{
    /// <summary>
    /// Create List Of Employee
    /// </summary>
    List<KeyValuePair<int, string>> employees = new List<KeyValuePair<int, string>>
    {
       new KeyValuePair<int,string>(1,"Abhijit"),
       new KeyValuePair<int,string>(2,"Rahul"),
       new KeyValuePair<int,string>(3,"Kunal"),
       new KeyValuePair<int,string>(4,"Atul"),
       new KeyValuePair<int,string>(5,"Abhishek"),
   };
<p>    /// <summary>
    /// Handles the Load event of the Page control.
    /// </summary>
    ///
<param name="sender">The source of the event.</param>
    ///
<param name="e">The <see cref="System.EventArgs"/> instance containing the event data.</param>
    protected void Page_Load(object sender, EventArgs e)
    {
        this.BindDropDownList();
        this.employees.Add(new KeyValuePair<int, string>(6, "Jony"));
        this.BindDropDownList();
    }
    /// <summary>
    /// Binds the drop down list.
    /// </summary>
    private void BindDropDownList()
    {
        dropDownListEmployee.DataSource = this.employees.OrderBy(item => item.Key);
        dropDownListEmployee.DataTextField = "Value";
        dropDownListEmployee.DataValueField = "Key";
        dropDownListEmployee.DataBind();
    }
  }
 

ASPX Page CodeSnippet

<%@ Page Language="C#" AutoEventWireup="true" CodeFile="Default.aspx.cs" Inherits="_Default" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title></title>
</head>
<body>
<form id="form1" runat="server">
<div>
        <asp:DropDownList ID="dropDownListEmployee" runat="server">
        </asp:DropDownList>
    </div>
</form>
<p></body>
</html>
 

Summary : In this blog post If have explained how to  bind a dropdown with List Of KeyValuePair elements and sort a  DropDownList items based in the DataTextField or DataValueField using LINQ

Hope this will help you !

Thanks !

AJ

Shout it


Filed under: .NET 4.0, ASP.NET, ASP.NET 4.0, General, Tips and Tricks

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)

About the Author

Abhijit Jana

Software Developer (Senior)

India India

Member

Follow on Twitter Follow on Twitter
.NET Consultant | Former Microsoft MVP - ASP.NET | CodeProject MVP, Mentor, Insiders| Technology Evangelist | Author | Speaker | Geek | Blogger | Husband
 
Blog : http://abhijitjana.net
Web Site : http://dailydotnettips.com
Twitter@AbhijitJana

Sign Up to vote   Poor Excellent
Add a reason or comment to your vote: x
Votes of 3 or less require a comment

Comments and Discussions

 
You must Sign In to use this message board. (secure sign-in)
 
Search this forum  
 FAQ
    Noise  Layout  Per page   
  Refresh
GeneralUsing with WinForms PinmemberMCofer10:41 17 Aug '10  
GeneralRe: Using with WinForms PinmemberMCofer11:10 17 Aug '10  
GeneralMy vote of 5 PinmentorKunalChowdhury6:15 9 Aug '10  
GeneralRe: My vote of 5 PinmvpAbhijit Jana9:44 10 Aug '10  
GeneralGood job PinmvpAbhishek Sur10:02 8 Aug '10  
GeneralRe: Good job Pinmembernikqwe20:41 9 Aug '10  
AnswerRe: Good job PinmentorKunalChowdhury23:07 9 Aug '10  
GeneralRe: Good job Pinmembernikqwe23:16 9 Aug '10  
GeneralRe: Good job PinmvpAbhijit Jana9:42 10 Aug '10  

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.

Permalink | Advertise | Privacy | Mobile
Web03 | 2.5.120515.1 | Last Updated 8 Aug 2010
Article Copyright 2010 by Abhijit Jana
Everything else Copyright © CodeProject, 1999-2012
Terms of Use
Layout: fixed | fluid