Sorting a DropDownList? - C#, ASP.NET

前端 未结 23 1122
慢半拍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 19:48

    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#

提交回复
热议问题