Sort items in a combobox or dropdownlist

by Emanuele 1/29/2008 5:03:00 PM

The DropDownList control does not expose a sort method to sort items by either the value or the displayed text.

If you pull the values from database, it's very simple because you just add the ORDER BY clause in the SQL SELECT statement.
But if you can't access on the database to modify the stored procedure or view, the solution is to load your data into an array and associate this to the combobox or dropdownlist.

With these simple lines, you can do it.

        private void btnSort_Click(object sender, EventArgs e)
        {
            ArrayList cboItems = new ArrayList();

            foreach (string item in cboCities.Items)
            {
                cboItems.Add(item);
                cboItems.TrimToSize();
            }

            cboItems.Sort();
            cboCities.Items.Clear();
            string[] Items = new string[cboItems.Count];

            cboItems.CopyTo(Items);
            cboCities.Items.AddRange(Items);
        }

 With some little fix, you can switch from combobox to dropdownlist.
On the link below you can find the source code with an example.

SortedList.zip (32.22 kb)

Related posts



Powered by BlogEngine.NET 1.3.1.0
Theme by Emanuele Bartolesi

About the author

Name of author Emanuele Bartolesi
I'm a senior developer and project manager.

Contact me Contact me

Calendar

<<  December 2008  >>
MoTuWeThFrSaSu
24252627282930
1234567
891011121314
15161718192021
22232425262728
2930311234

View posts in large calendar

Disclaimer

The opinions expressed herein are my own personal opinions and do not represent my employer's view in anyway.

© Copyright 2008

Sign in

Download Day 2008