[c#] Sorting a DropDownList? - C#, ASP.NET

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.

This question is related to c# asp.net drop-down-menu

The answer is


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


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.


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.


Try This:

/// <summary>
/// AlphabetizeDropDownList alphabetizes a given dropdown list by it's displayed text.
/// </summary>
/// <param name="dropDownList">The drop down list you wish to modify.</param>
/// <remarks></remarks>
private void AlphabetizeDropDownList(ref DropDownList dropDownList)
{
    //Create a datatable to sort the drop down list items
    DataTable machineDescriptionsTable = new DataTable();
    machineDescriptionsTable.Columns.Add("DescriptionCode", typeof(string));
    machineDescriptionsTable.Columns.Add("UnitIDString", typeof(string));
    machineDescriptionsTable.AcceptChanges();
    //Put each of the list items into the datatable
    foreach (ListItem currentDropDownListItem in dropDownList.Items) {
            string currentDropDownUnitIDString = currentDropDownListItem.Value;
            string currentDropDownDescriptionCode = currentDropDownListItem.Text;
            DataRow currentDropDownDataRow = machineDescriptionsTable.NewRow();
            currentDropDownDataRow["DescriptionCode"] = currentDropDownDescriptionCode.Trim();
            currentDropDownDataRow["UnitIDString"] = currentDropDownUnitIDString.Trim();
            machineDescriptionsTable.Rows.Add(currentDropDownDataRow);
            machineDescriptionsTable.AcceptChanges();
    }
    //Sort the data table by description
    DataView sortedView = new DataView(machineDescriptionsTable);
    sortedView.Sort = "DescriptionCode";
    machineDescriptionsTable = sortedView.ToTable();
    //Clear the items in the original dropdown list
    dropDownList.Items.Clear();
    //Create a dummy list item at the top
    ListItem dummyListItem = new ListItem(" ", "-1");
    dropDownList.Items.Add(dummyListItem);
    //Begin transferring over the items alphabetically from the copy to the intended drop
     downlist
    foreach (DataRow currentDataRow in machineDescriptionsTable.Rows) {
            string currentDropDownValue = currentDataRow["UnitIDString"].ToString().Trim();
            string currentDropDownText = currentDataRow["DescriptionCode"].ToString().Trim();
            ListItem currentDropDownListItem = new ListItem(currentDropDownText, currentDropDownValue);
    //Don't deal with dummy values in the list we are transferring over
    if (!string.IsNullOrEmpty(currentDropDownText.Trim())) {
        dropDownList.Items.Add(currentDropDownListItem);
    }
}

}

This will take a given drop down list with a Text and a Value property of the list item and put them back into the given drop down list. Best of Luck!


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();

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.


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.


DropDownList takes any IEnumerable as a DataSource.

Just sort it using LINQ.


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.


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).


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.


You can use this JavaScript function:

function sortlist(mylist)
{
   var lb = document.getElementById(mylist);
   arrTexts = new Array();
   arrValues = new Array();
   arrOldTexts = new Array();

   for(i=0; i<lb.length; i++)
   {
      arrTexts[i] = lb.options[i].text;
      arrValues[i] = lb.options[i].value;

      arrOldTexts[i] = lb.options[i].text;
   }

   arrTexts.sort();

   for(i=0; i<lb.length; i++)
   {
      lb.options[i].text = arrTexts[i];
      for(j=0; j<lb.length; j++)
      {
         if (arrTexts[i] == arrOldTexts[j])
         {
            lb.options[i].value = arrValues[j];
            j = lb.length;
         }
      }
   }
}

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.


If you are using a data bounded DropDownList, just go to the wizard and edit the bounding query by:

  1. Goto the .aspx page (design view).
  2. Click the magic Arrow ">"on the Dropdown List.
  3. Select "Configure Data source".
  4. Click Next.
  5. On the right side of the opened window click "ORDER BY...".
  6. You will have up two there field cariteria to sort by. Select the desired field and click OK, then click Finish.

enter image description here


is better if you sort the Source before Binding it to DropDwonList. but sort DropDownList.Items like this:

    Dim Lista_Items = New List(Of ListItem)

    For Each item As ListItem In ddl.Items
        Lista_Items.Add(item)
    Next

    Lista_Items.Sort(Function(x, y) String.Compare(x.Text, y.Text))

    ddl.Items.Clear()
    ddl.Items.AddRange(Lista_Items.ToArray())

(this case i sort by a string(the item's text), it could be the suplier's name, supplier's id)

the Sort() method is for every List(of ) / List<MyType>, you can use it.


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" />

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.


Try This:

/// <summary>
/// AlphabetizeDropDownList alphabetizes a given dropdown list by it's displayed text.
/// </summary>
/// <param name="dropDownList">The drop down list you wish to modify.</param>
/// <remarks></remarks>
private void AlphabetizeDropDownList(ref DropDownList dropDownList)
{
    //Create a datatable to sort the drop down list items
    DataTable machineDescriptionsTable = new DataTable();
    machineDescriptionsTable.Columns.Add("DescriptionCode", typeof(string));
    machineDescriptionsTable.Columns.Add("UnitIDString", typeof(string));
    machineDescriptionsTable.AcceptChanges();
    //Put each of the list items into the datatable
    foreach (ListItem currentDropDownListItem in dropDownList.Items) {
            string currentDropDownUnitIDString = currentDropDownListItem.Value;
            string currentDropDownDescriptionCode = currentDropDownListItem.Text;
            DataRow currentDropDownDataRow = machineDescriptionsTable.NewRow();
            currentDropDownDataRow["DescriptionCode"] = currentDropDownDescriptionCode.Trim();
            currentDropDownDataRow["UnitIDString"] = currentDropDownUnitIDString.Trim();
            machineDescriptionsTable.Rows.Add(currentDropDownDataRow);
            machineDescriptionsTable.AcceptChanges();
    }
    //Sort the data table by description
    DataView sortedView = new DataView(machineDescriptionsTable);
    sortedView.Sort = "DescriptionCode";
    machineDescriptionsTable = sortedView.ToTable();
    //Clear the items in the original dropdown list
    dropDownList.Items.Clear();
    //Create a dummy list item at the top
    ListItem dummyListItem = new ListItem(" ", "-1");
    dropDownList.Items.Add(dummyListItem);
    //Begin transferring over the items alphabetically from the copy to the intended drop
     downlist
    foreach (DataRow currentDataRow in machineDescriptionsTable.Rows) {
            string currentDropDownValue = currentDataRow["UnitIDString"].ToString().Trim();
            string currentDropDownText = currentDataRow["DescriptionCode"].ToString().Trim();
            ListItem currentDropDownListItem = new ListItem(currentDropDownText, currentDropDownValue);
    //Don't deal with dummy values in the list we are transferring over
    if (!string.IsNullOrEmpty(currentDropDownText.Trim())) {
        dropDownList.Items.Add(currentDropDownListItem);
    }
}

}

This will take a given drop down list with a Text and a Value property of the list item and put them back into the given drop down list. Best of Luck!


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.


var list = ddl.Items.Cast<ListItem>().OrderBy(x => x.Text).ToList();

ddl.DataSource = list;
ddl.DataTextField = "Text";
ddl.DataValueField = "Value"; 
ddl.DataBind();

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" />

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();

        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();

is better if you sort the Source before Binding it to DropDwonList. but sort DropDownList.Items like this:

    Dim Lista_Items = New List(Of ListItem)

    For Each item As ListItem In ddl.Items
        Lista_Items.Add(item)
    Next

    Lista_Items.Sort(Function(x, y) String.Compare(x.Text, y.Text))

    ddl.Items.Clear()
    ddl.Items.AddRange(Lista_Items.ToArray())

(this case i sort by a string(the item's text), it could be the suplier's name, supplier's id)

the Sort() method is for every List(of ) / List<MyType>, you can use it.


You can use this JavaScript function:

function sortlist(mylist)
{
   var lb = document.getElementById(mylist);
   arrTexts = new Array();
   arrValues = new Array();
   arrOldTexts = new Array();

   for(i=0; i<lb.length; i++)
   {
      arrTexts[i] = lb.options[i].text;
      arrValues[i] = lb.options[i].value;

      arrOldTexts[i] = lb.options[i].text;
   }

   arrTexts.sort();

   for(i=0; i<lb.length; i++)
   {
      lb.options[i].text = arrTexts[i];
      for(j=0; j<lb.length; j++)
      {
         if (arrTexts[i] == arrOldTexts[j])
         {
            lb.options[i].value = arrValues[j];
            j = lb.length;
         }
      }
   }
}

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.


If you are adding options to the dropdown one by one without a dataset and you want to sort it later after adding items, here's a solution:

DataTable dtOptions = new DataTable();
DataColumn[] dcColumns = { new DataColumn("Text", Type.GetType("System.String")), 
                           new DataColumn("Value", Type.GetType("System.String"))};
dtOptions.Columns.AddRange(dcColumns);
foreach (ListItem li in ddlOperation.Items)
{
   DataRow dr = dtOptions.NewRow();
   dr["Text"] = li.Text;
   dr["Value"] = li.Value;
   dtOptions.Rows.Add(dr);
}
DataView dv = dtOptions.DefaultView;
dv.Sort = "Text";
ddlOperation.Items.Clear();
ddlOperation.DataSource = dv;
ddlOperation.DataTextField = "Text";
ddlOperation.DataValueField = "Value";
ddlOperation.DataBind();

This would sort the dropdown items in alphabetical order.


You can do it this way is simple

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);
}

}

And call the method this SortDDL(ref yourDropDownList); and that's it. The data in your dropdownlist will be sorted.

see http://www.codeproject.com/Articles/20131/Sorting-Dropdown-list-in-ASP-NET-using-C#


Another option is to put the ListItems into an array and sort.

        int i = 0;
        string[] array = new string[items.Count];

        foreach (ListItem li in dropdownlist.items)
        {
            array[i] = li.ToString();
            i++;

        }

        Array.Sort(array);

        dropdownlist.DataSource = array;
        dropdownlist.DataBind();

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


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).


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


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.


Another option is to put the ListItems into an array and sort.

        int i = 0;
        string[] array = new string[items.Count];

        foreach (ListItem li in dropdownlist.items)
        {
            array[i] = li.ToString();
            i++;

        }

        Array.Sort(array);

        dropdownlist.DataSource = array;
        dropdownlist.DataBind();

You can do it this way is simple

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);
}

}

And call the method this SortDDL(ref yourDropDownList); and that's it. The data in your dropdownlist will be sorted.

see http://www.codeproject.com/Articles/20131/Sorting-Dropdown-list-in-ASP-NET-using-C#


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.


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


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.


If you are adding options to the dropdown one by one without a dataset and you want to sort it later after adding items, here's a solution:

DataTable dtOptions = new DataTable();
DataColumn[] dcColumns = { new DataColumn("Text", Type.GetType("System.String")), 
                           new DataColumn("Value", Type.GetType("System.String"))};
dtOptions.Columns.AddRange(dcColumns);
foreach (ListItem li in ddlOperation.Items)
{
   DataRow dr = dtOptions.NewRow();
   dr["Text"] = li.Text;
   dr["Value"] = li.Value;
   dtOptions.Rows.Add(dr);
}
DataView dv = dtOptions.DefaultView;
dv.Sort = "Text";
ddlOperation.Items.Clear();
ddlOperation.DataSource = dv;
ddlOperation.DataTextField = "Text";
ddlOperation.DataValueField = "Value";
ddlOperation.DataBind();

This would sort the dropdown items in alphabetical order.


Try it

-------Store Procedure-----(SQL)

USE [Your Database]
GO


CRATE PROC [dbo].[GetAllDataByID]

@ID int


AS
BEGIN
        SELECT * FROM Your_Table
        WHERE ID=@ID
        ORDER BY Your_ColumnName 
END

----------Default.aspx---------

<asp:DropDownList ID="ddlYourTable" runat="server"></asp:DropDownList>

---------Default.aspx.cs-------

protected void Page_Load(object sender, EventArgs e)

{

      if (!IsPostBack)
            {
                List<YourTable> table= new List<YourTable>();

                YourtableRepository tableRepo = new YourtableRepository();

                int conuntryInfoID=1;

                table= tableRepo.GetAllDataByID(ID);

                ddlYourTable.DataSource = stateInfo;
                ddlYourTable.DataTextField = "Your_ColumnName";
                ddlYourTable.DataValueField = "ID";
                ddlYourTable.DataBind();

            }
        }

-------LINQ Helper Class----

public class TableRepository

   {

        string connstr;

        public TableRepository() 
        {
            connstr = Settings.Default.YourTableConnectionString.ToString();
        }

        public List<YourTable> GetAllDataByID(int ID)
        {
            List<YourTable> table= new List<YourTable>();
            using (YourTableDBDataContext dc = new YourTableDBDataContext ())
            {
                table= dc.GetAllDataByID(ID).ToList();
            }
            return table;
        }
    }

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.


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();

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).


DropDownList takes any IEnumerable as a DataSource.

Just sort it using LINQ.


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.


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.


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.


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();

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#


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.


If you are using a data bounded DropDownList, just go to the wizard and edit the bounding query by:

  1. Goto the .aspx page (design view).
  2. Click the magic Arrow ">"on the Dropdown List.
  3. Select "Configure Data source".
  4. Click Next.
  5. On the right side of the opened window click "ORDER BY...".
  6. You will have up two there field cariteria to sort by. Select the desired field and click OK, then click Finish.

enter image description here


You can use this JavaScript function:

function sortlist(mylist)
{
   var lb = document.getElementById(mylist);
   arrTexts = new Array();
   arrValues = new Array();
   arrOldTexts = new Array();

   for(i=0; i<lb.length; i++)
   {
      arrTexts[i] = lb.options[i].text;
      arrValues[i] = lb.options[i].value;

      arrOldTexts[i] = lb.options[i].text;
   }

   arrTexts.sort();

   for(i=0; i<lb.length; i++)
   {
      lb.options[i].text = arrTexts[i];
      for(j=0; j<lb.length; j++)
      {
         if (arrTexts[i] == arrOldTexts[j])
         {
            lb.options[i].value = arrValues[j];
            j = lb.length;
         }
      }
   }
}

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.


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).


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.


var list = ddl.Items.Cast<ListItem>().OrderBy(x => x.Text).ToList();

ddl.DataSource = list;
ddl.DataTextField = "Text";
ddl.DataValueField = "Value"; 
ddl.DataBind();

DropDownList takes any IEnumerable as a DataSource.

Just sort it using LINQ.


Try it

-------Store Procedure-----(SQL)

USE [Your Database]
GO


CRATE PROC [dbo].[GetAllDataByID]

@ID int


AS
BEGIN
        SELECT * FROM Your_Table
        WHERE ID=@ID
        ORDER BY Your_ColumnName 
END

----------Default.aspx---------

<asp:DropDownList ID="ddlYourTable" runat="server"></asp:DropDownList>

---------Default.aspx.cs-------

protected void Page_Load(object sender, EventArgs e)

{

      if (!IsPostBack)
            {
                List<YourTable> table= new List<YourTable>();

                YourtableRepository tableRepo = new YourtableRepository();

                int conuntryInfoID=1;

                table= tableRepo.GetAllDataByID(ID);

                ddlYourTable.DataSource = stateInfo;
                ddlYourTable.DataTextField = "Your_ColumnName";
                ddlYourTable.DataValueField = "ID";
                ddlYourTable.DataBind();

            }
        }

-------LINQ Helper Class----

public class TableRepository

   {

        string connstr;

        public TableRepository() 
        {
            connstr = Settings.Default.YourTableConnectionString.ToString();
        }

        public List<YourTable> GetAllDataByID(int ID)
        {
            List<YourTable> table= new List<YourTable>();
            using (YourTableDBDataContext dc = new YourTableDBDataContext ())
            {
                table= dc.GetAllDataByID(ID).ToList();
            }
            return table;
        }
    }

        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();

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.


DropDownList takes any IEnumerable as a DataSource.

Just sort it using LINQ.


You can use this JavaScript function:

function sortlist(mylist)
{
   var lb = document.getElementById(mylist);
   arrTexts = new Array();
   arrValues = new Array();
   arrOldTexts = new Array();

   for(i=0; i<lb.length; i++)
   {
      arrTexts[i] = lb.options[i].text;
      arrValues[i] = lb.options[i].value;

      arrOldTexts[i] = lb.options[i].text;
   }

   arrTexts.sort();

   for(i=0; i<lb.length; i++)
   {
      lb.options[i].text = arrTexts[i];
      for(j=0; j<lb.length; j++)
      {
         if (arrTexts[i] == arrOldTexts[j])
         {
            lb.options[i].value = arrValues[j];
            j = lb.length;
         }
      }
   }
}

Examples related to c#

How can I convert this one line of ActionScript to C#? Microsoft Advertising SDK doesn't deliverer ads How to use a global array in C#? How to correctly write async method? C# - insert values from file into two arrays Uploading into folder in FTP? Are these methods thread safe? dotnet ef not found in .NET Core 3 HTTP Error 500.30 - ANCM In-Process Start Failure Best way to "push" into C# array

Examples related to asp.net

RegisterStartupScript from code behind not working when Update Panel is used You must add a reference to assembly 'netstandard, Version=2.0.0.0 No authenticationScheme was specified, and there was no DefaultChallengeScheme found with default authentification and custom authorization How to use log4net in Asp.net core 2.0 Visual Studio 2017 error: Unable to start program, An operation is not legal in the current state How to create roles in ASP.NET Core and assign them to users? How to handle Uncaught (in promise) DOMException: The play() request was interrupted by a call to pause() ASP.NET Core Web API Authentication Could not load file or assembly 'CrystalDecisions.ReportAppServer.CommLayer, Version=13.0.2000.0 WebForms UnobtrusiveValidationMode requires a ScriptResourceMapping for jquery How to implement drop down list in flutter? How can I create a dropdown menu from a List in Tkinter? How can I close a dropdown on click outside? Making a drop down list using swift? HTML: Select multiple as dropdown How to get selected value of a dropdown menu in ReactJS Avoid dropdown menu close on click inside Bootstrap 3 dropdown select How to make a drop down list in yii2? Android custom dropdown/popup menu