Tuesday, February 1, 2011

Sorting a DropDownList using Array list

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)

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;
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());

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

Anil Kumare Pandey