Asp.net: How to sort a dropdown list with duplicates?

I have a dropdown where we add some items after the dropdown is linked by data from the db so it becomes necessary to sort the dropdown. So I need to sort the dropdown that may have duplicates. What's the best way to do this?

0


source to share


2 answers


Instead of adding items directly to the dropdown, I would suggest adding them to the data structure you are binding to. If the elements in this structure are implemented IComparable

, then you can define a comparison method to apply the sort before Dropdown is actually bound to the data source.



+2


source


Assuming you are binding to the Shared List, you can try something like this:



    var ddlFoo = new List<foo>();
    foreach (var lc in myDropDownList.Items)
    {
        ddlFoo.Add((foo)lc);
    }
    myDropDownList.DataSource = ddlFoo.OrderBy(dl => dl.fooID);
    myDropDownList.Databind();

      

0


source







All Articles