locked
How to sort data in a dropdown list RRS feed

  • Question

  • User-1664485818 posted

    Hi folks, I'm trying to sort data for a dropdown list by Orderby.

    The Orderby is not working!!

       ddlMake.DataSource = (from d in dbcontext.Tyres
                                              orderby d.Make 
                                              select new {d.Make}).Distinct().ToList();

    Tuesday, August 2, 2016 7:50 PM

Answers

  • User-1034726716 posted

    Try making a Distinct call before doing an OrderBy. For example:

    var data = (from d in dbcontext.Tyres
                          select new {d.Make})
                         .Distinc()
    		     .OrderBy(d => d.Make);
    
    ddlMake.DataSource = data.ToList();
    ddlMake.DataBind();

    • Marked as answer by Anonymous Thursday, October 7, 2021 12:00 AM
    Wednesday, August 3, 2016 10:59 AM

All replies

  • User-359936451 posted

    Try something like this....

    http://www.functionx.com/csharp/linq/Lesson03.htm

    list = list.OrderByDescending(x => x.AVC)
               .ToList();

    or

    DataContext dc = ...;
    
    DataShape s = new DataShape();
    
    s.AssociateWith<Customer>(c => from o in c.Orders order by o.OrderDate select o);
    
    dc.Shape = s;
    

    or

    https://msdn.microsoft.com/en-us/library/bb882684.aspx

    Tuesday, August 2, 2016 8:55 PM
  • User-1034726716 posted

    Try making a Distinct call before doing an OrderBy. For example:

    var data = (from d in dbcontext.Tyres
                          select new {d.Make})
                         .Distinc()
    		     .OrderBy(d => d.Make);
    
    ddlMake.DataSource = data.ToList();
    ddlMake.DataBind();

    • Marked as answer by Anonymous Thursday, October 7, 2021 12:00 AM
    Wednesday, August 3, 2016 10:59 AM
  • User-271186128 posted

    Hi brucey,

    I create a sample using the code like you used, It works fine in my application.

    using (CategoriesEnyities entities = new CategoriesEnyities())
                    {        
                        var ds= (from d in entities.Categories
                                   orderby d.CategoryName
                                   select d.CategoryName).Distinct().ToList();
                        DropDownList1.DataSource = ds;
                        DropDownList1.DataBind();
                        DropDownList1.DataTextField = "CategoryName";
                        DropDownList1.DataValueField = "CategoryName";
                    }
    

    The output screenshot as below.

    Besides, you can also try the method vinz provided. It’s working too in my computer. After you tried, if the Orderby is still not working, you could provide some data you want to bind to your DropDownList and more code about how you bind data to your DropDownList. It might be easier for us to guide you and help you find the reason for your problem timely.

    Best regards,
    Dillion

    Thursday, August 4, 2016 10:05 AM