views:

10667

answers:

17

I'm curious as to the best route (more looking towards simplicity, not speed or efficiency) to sort a DropDownList in C#/ASP.NET - I've looked at a few recommendations but they aren't clicking well with me.

Edit: Folks, I do not have control over how the data comes into the DropDownList - I cannot modify the SQL.

+3  A: 

I usually load a DropDownList with values from a database table, so the easiest way is to sort your results as desired with the ORDER BY clause of your SELECT statement, and then just iterate through the results and dump them into the DropDownList.

MusiGenesis
OP indicates he cannot modify the SQL used to populate this dropdown
DaveJustDave
A: 

If the values in the DropDownList are data driven, I usually sort the data in the SQL statement by whatever the value ends up being.

Anthony Potts
+9  A: 

DropDownList takes any IEnumerable as a DataSource.

Just sort it using LINQ.

Jim
A: 

I agree with the folks in sorting your data in the model before populating them to the DropDownList, so if you are populating this from a DB, it is a good thing to get them sorted already there using a simple order by clause, it will save you some cycles in the web server, and I am sure the DB will do it so much faster. If you are populating this from another data source for example, XML file, using LINQ will be a good idea, or even any variation of Array.Sort will be good.

bashmohandes
+1  A: 

I agree with sorting using ORDER BY when populating with a database query, if all you want is to sort the displayed results alphabetically. Let the database engine do the work of sorting.

However, sometimes you want some other sort order besides alphabetical. For example, you might want a logical sequence like: New, Open, In Progress, Completed, Approved, Closed. In that case, you could add a column to the database table to explicitly set the sort order. Name it something like SortOrder or DisplaySortOrder. Then, in your SQL, you'd ORDER BY the sort order field (without retrieving that field).

DOK
A: 

MusiGenesis has it right - sort the data at the source.

David Robbins
A: 

If your data is coming to you as a System.Data.DataTable, call the DataTable's .Select() method, passing in "" for the filterExpression and "COLUMN1 ASC" (or whatever column you want to sort by) for the sort. This will return an array of DataRow objects, sorted as specified, that you can then iterate through and dump into the DropDownList.

MusiGenesis
+2  A: 

Take a look at the this article from CodeProject, which rearranges the content of a dropdownlist. If you are databinding, you will need to run the sorter after the data is bound to the list.

Samuel Kim
+1  A: 

What kind of object are you using for databinding? Typically I use Collection<T>, List<T>, or Queue<T> (depending on circumstances). These are relatively easy to sort using a custom delegate. See MSDN documentation on the Comparison(T) delegate.

sfuqua
Thanks, I think this is the best way to do this. In my case, I'm using properties of a data set to load a "filters" dropdown. By adding each property to a list when getting the data, I can sort the list later and databind to my dropdown when needed. Also allows tweaking of filters in list for any text changes.Thanks!
Jason
+6  A: 

Assuming you are running the latest version of the .Net Framework this will work:

List<string> items = GetItemsFromSomewhere();
items.Sort((x, y) => string.Compare(x, y));
DropDownListId.DataSource = items;
DropDownListId.DataBind();
SaaS Developer
A: 

You may not have access to the SQL, but if you have the DataSet or DataTable, you can certainly call the Sort() method.

Kon
If either one had a Sort method, you could.
MusiGenesis
+4  A: 

If you get a DataTable with the data, you can create a DataView off of this and then bind the drop down list to that. Your code would look something like...

DataView dvOptions = new DataView(DataTableWithOptions);
dvOptions.Sort = "Description";

ddlOptions.DataSource = dvOptions;
ddlOptions.DataTextField = "Description";
ddlOptions.DataValueField = "Id";
ddlOptions.DataBind();

Your text field and value field options are mapped to the appropriate columnns in the data table you are receiving.

Dillie-O
A: 
+1  A: 

It is recommended to sort the data before databinding it to the DropDownList but in case you can not, this is how you would sort the items in the DropDownList.

First you need a comparison class

Public Class ListItemComparer
    Implements IComparer(Of ListItem)

    Public Function Compare(ByVal x As ListItem, ByVal y As ListItem) As Integer _
        Implements IComparer(Of ListItem).Compare

        Dim c As New CaseInsensitiveComparer
        Return c.Compare(x.Text, y.Text)
    End Function
End Class

Then you need a method that will use this Comparer to sort the DropDownList

Public Shared Sub SortDropDown(ByVal cbo As DropDownList)
    Dim lstListItems As New List(Of ListItem)
    For Each li As ListItem In cbo.Items
        lstListItems.Add(li)
    Next
    lstListItems.Sort(New ListItemComparer)
    cbo.Items.Clear()
    cbo.Items.AddRange(lstListItems.ToArray)
End Sub

Finally, call this function with your DropDownList (after it's been databound)

SortDropDown(cboMyDropDown)

P.S. Sorry but my choice of language is VB. You can use http://converter.telerik.com/ to convert the code from VB to C#

dDejan
A: 
        List<ListItem> li = new List<ListItem>();
        foreach (ListItem list in DropDownList1.Items)
        {
            li.Add(list);
        }
        li.Sort((x, y) => string.Compare(x.Text, y.Text));
        DropDownList1.Items.Clear();
        DropDownList1.DataSource = li;
        DropDownList1.DataTextField = "Text";
        DropDownList1.DataValueField = "Value";
        DropDownList1.DataBind();
Randy
+1  A: 

A C# solution for .NET 3.5 (needs System.Linq and System.Web.UI):

    public static void ReorderAlphabetized(this DropDownList ddl)
    {
        List<ListItem> listCopy = new List<ListItem>();
        foreach (ListItem item in ddl.Items)
            listCopy.Add(item);
        ddl.Items.Clear();
        foreach (ListItem item in listCopy.OrderBy(item => item.Text))
            ddl.Items.Add(item);
    }

Call it after you've bound your dropdownlist, e.g. OnPreRender:

    protected override void OnPreRender(EventArgs e)
    {
        base.OnPreRender(e);
        ddlMyDropDown.ReorderAlphabetized();
    }

Stick it in your utility library for easy re-use.

James McCormack
A: 

To sort an object datasource that returns a dataset you use the Sort property of the control.

Example usage In the aspx page to sort by ascending order of ColumnName

<asp:ObjectDataSource ID="dsData" runat="server" TableName="Data" 
 Sort="ColumnName ASC" />
mikek3332002