Introduction
I found a big problem in ASP.NET is there was no direct method for sorting the items in the Dropdown list. Sometimes this sorting functionality is required in the applications.
Here I gave a small and easy technique of sorting the Dropdown list in ASP.NET
Using the code
I assumed that, you have a Dropdown list in your ASPX page with name "DropDownList1". I have added few items to this Dropdown list in the Page_Load event with disorder manner.
protected void Page_Load(object sender, EventArgs e)
{
this.DropDownList1.Items.Add("Orange");
this.DropDownList1.Items.Add("Grapes");
this.DropDownList1.Items.Add("Apple");
this.DropDownList1.Items.Add("Mango");
this.DropDownList1.Items.Add("Lemon");
this.DropDownList1.Items.Add("Banana");
SortDDL(ref this.DropDownList1);
}
In the Page_Load event, I have called a function "SortDDL" for sorting the Dropdown list. In this function we have to pass the reference of the required Dropdown list. Then system will automatically sort the items in the given Dropdown list.
private void SortDDL(ref DropDownList objDDL)
{
ArrayList textList = new ArrayList();
ArrayList valueList = new ArrayList();
foreach (ListItem li in objDDL.Items)
{
textList.Add(li.Text);
}
textList.Sort();
foreach (object item in textList)
{
string value = objDDL.Items.FindByText(item.ToString()).Value;
valueList.Add(value);
}
objDDL.Items.Clear();
for(int i = 0; i < textList.Count; i++)
{
ListItem objItem = new ListItem(textList[i].ToString(), valueList[i].ToString());
objDDL.Items.Add(objItem);
}
}
We should need to import the following namespace for getting ArrayList class.
"TEXT-INDENT: 0.5in">using System.Collections;
Happy Coding to All!!