Click here to Skip to main content
15,881,812 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
Hi Guys

Currently i have an issue trying to sort a listbox, issue i am having is i have tried to sort by the attributes but not having any luck

I need to do the sort on 3 different attributes
sort by
Attribute1

then
Attribute2

then
Attribute3



but having no luck

What I have tried:

public class CustomComparer : System.Collections.IComparer
       {
           public int Compare(object x, object y)
           {
               RadListBoxItem p1 = new RadListBoxItem();
               RadListBoxItem p2 = new RadListBoxItem();
               if (x is RadListBoxItem)
                   p1 = x as RadListBoxItem;
               else
                   throw new ArgumentException("Object is not of type RadListBoxItem.");
               if (y is RadListBoxItem)
                   p2 = y as RadListBoxItem;
               else
                   throw new ArgumentException("Object is not of type RadListBoxItem.");
               int cmp = 0;
               if (p1.ListBox.Sort == RadListBoxSort.Ascending)
               {
                   //here we compare the Values of the items
                   if (String.Compare(p1.Value, p2.Value, !p1.ListBox.SortCaseSensitive) == 0)
                   {
                       return 0;
                   }
                   if (String.Compare(p1.Attributes["Attribute1"], p2.Attributes["AgentHierachy"], !p1.ListBox.SortCaseSensitive) == 0)
                   {
                       return 0;
                   }
                   if (String.Compare(p1.Attributes["Attribute2"], p2.Attributes["SubAgentID"], !p1.ListBox.SortCaseSensitive)==0)
                   {
                       return 0;
                   }

               }
               if (p1.ListBox.Sort == RadListBoxSort.Descending)
               {
                   //here we compare the Values of the items
                   cmp = String.Compare(p1.Value, p2.Value, !p1.ListBox.SortCaseSensitive) * -1;
               }
               return cmp;
           }
Posted
Updated 8-Mar-18 4:18am
Comments
Maciej Los 8-Mar-18 10:45am    
Sorry, but you're trying to sort ListBox items instead of data?

1 solution

If this is WPF, you could simply sort the collection that's bound to the control using Linq:

C#
collection.OrderBy(x=>x.Property1).ThenBy(x=>x.Property2).ThenBy(x=>x.Property3)


Of course, this is just conceptual code that you'll have to adapt to your code.
 
Share this answer
 
Comments
Maciej Los 8-Mar-18 10:46am    
Good idea!

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900