Sorting a DropDownList? - C#, ASP.NET

前端 未结 23 1047
慢半拍i
慢半拍i 2020-12-08 19: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 b

相关标签:
23条回答
  • 2020-12-08 20:09

    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" />
    
    0 讨论(0)
  • 2020-12-08 20:10

    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();
    
    0 讨论(0)
  • 2020-12-08 20:11

    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.

    0 讨论(0)
  • 2020-12-08 20:11

    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.

    0 讨论(0)
  • 2020-12-08 20:12

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

    0 讨论(0)
提交回复
热议问题