How to sort dropdownlist using arraylist.


In this code snippets, we can see that How can we Sort a DropDownList with the help of Array List. What we do is simply copy the each value first in an ArrayList then sort that array list, after that we will also copy the value of each item in another array list and after that based on each key we will assing the value to the array list and finaaly back to the drop downliast.

Hello All,
We frequently make use of the Dropdownlost to display some list items, that may be country name, city name, Postcode , User Name and so many other things. At time we do not have the option to SORT all the list item. In this Code snippet, With the help of the ArrayList we can sort the items inside a DropDown.

The Array List is having a Inbuilt Sorting method which we can make use to sort any list. We simply Copy the Text and Value field of the Dropdown items inside 2 separate ArrayList and then We will add the Items from the Arry List to the DropDown.

Here is the Sample Code.


SortDropDown(ref ddlName); //Calling Method


private void SortDropDown(ref DropDownList objDDL)
{
// Decalre 2 ArryList to Hold the Text and Value of Items
ArrayList alText= new ArrayList();
ArrayList alValue = new ArrayList();


//Copy the Text field in the First Arry List
foreach (ListItem li in objDDL.Items)
{
alTextt.Add(li.Text);
}

alText.Sort(); //Sort the First Array List


//Copy the value field in the Second Array List based on First ArrayList value
foreach (object item in alText)
{
string val = objDDL.Items.FindByText(item.ToString()).Value;
alValue.Add(val);
}
objDDL.Items.Clear(); //Clear the Dropdown

//Finally Add the Sorted Value in DropDown
for(int intIndex = 0; intIndex < textList.Count; intIndex++)
{
ListItem itm = new ListItem(alText[intIndex].ToString(), alValue[intIndex].ToString());
objDDL.Items.Add(itm);
}
}



Hope you got this Clear idea about sorting the Arraylist. In cvase of Any issue Please send a Message.

Thanks
Anil Kumar Pandey

Reference: http://www.mannpandey.blogspot.com/


Comments

Author: Anil Kumar Pandey21 Feb 2011 Member Level: Diamond   Points : 1

Who ever is the resource editor , Please do not time pass what ever comment you have to give, give at one time.

This is too irritating that for a single line of change you take this much time. Whoever is the resource editor talk with me on my gmail Id.

Author: Timothy Vandeweerd13 Nov 2014 Member Level: Bronze   Points : 2

Excellent article. Thank you!

Can someone please help with the sub call when converting to VB?

SortDropDown(DropDownList1)

'Value of type 'System.Web.UI.WebControls.DropDownList' cannot be converted to 'WebApplication1.DropDownList'.



  • Do not include your name, "with regards" etc in the comment. Write detailed comment, relevant to the topic.
  • No HTML formatting and links to other web sites are allowed.
  • This is a strictly moderated site. Absolutely no spam allowed.
  • Name:
    Email: