Thursday, September 9, 2010

C#: Sort DropDownList

public void SortDropDownList(ref DropDownList ddl)
{
DropDownList ddlClone = new DropDownList();
foreach (ListItem item in ddl.Items)
{
ddlClone.Items.Add(item);
}
var query = ddlClone.Items.Cast().OrderBy(o => o.Text);
ddl.Items.Clear();
foreach (var item in query)
{
ddl.Items.Add(item);
}
}

3 comments:

  1. Great blog!
    Thanks for sharing.

    --------
    Tenax Technologies is a Belarussian software company delivering complex web solutions. We provide comprehensive software development for startups based on Java J2EE Spring Hibernate web2.0 technologies.

    ReplyDelete
  2. Or you might create extension method on DropDownList class. The solution code might be cleaner.

    ReplyDelete
  3. Dear "Interview Questions",
    I appreciate your taking time to comment, and you are absolutely correct; that would be the optimum way to get it.
    However as you would notice, most of my posts are rather stand-alone quick tricks to get the job done with minimal code, and not necessarily optimized or scaled for large scale consumption. Some times we just need a quick way to get stupid things done :-)
    Please do keep visiting, and share your thoughts like above.
    Cheers!

    ReplyDelete

Please use your common sense before making a comment, and I truly appreciate your constructive criticisms.