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 Kumar Pandey
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.
Excellent article. Thank you!
Can someone please help with the sub call when converting to VB?
'Value of type 'System.Web.UI.WebControls.DropDownList' cannot be converted to 'WebApplication1.DropDownList'.