Tuesday, July 28, 2009

How to sort a drop down list in C#.

There is no built in method available to sort a dropdown or any list in C#, thought to share with you guys.

#region SortDropDownList

public void SortDropDownList(DropDownList ddl)
{
//create a ListItem array the size of the items
//in your DropDownList
ListItem[] sorted = new ListItem[ddl.Items.Count];
//loop through all the items in your ListItem array
for (int i = 0; i < sorted.Length; i++)
{
//resize the array on each iteration
Array.Resize(ref sorted, i);
//add the current index to the array
sorted[i] = ddl.Items[i];
}
//call Array.Sort to sort your ListItem array
Array.Sort(sorted);
//remove all items from the DropDownList
ddl.Items.Clear();
//add the sorted items to the DropDownList
ddl.Items.AddRange(sorted);
}
#endregion

No comments:

Post a Comment