Posted by: Zeeshan Amjad | January 24, 2010

Sorting items in a list box


Sorting an items in a list box is very easy and there are more than one approaches to do this. Here we are going to discuss one very simple approach. We are going to create an object of ObservableCollection class. The main reason is that whenever there is any change in the collection, then it will automatically update in the list box using the data binding. Then we will use the SortDescription structure to specify not only the sorting order, but also in which field we want to sort.

Here is our class to define the class to store information about states.

  1: public class StateInfo
  2: {
  3:     public StateInfo(string name, string capital, string bigcity, string nickname)
  4:     {
  5:         Name = name;
  6:         Capital = capital;
  7:         BigCity = bigcity;
  8:         NickName = nickname;
  9:     }
 10: 
 11:     public string Name
 12:     { get; set; }
 13: 
 14:     public string Capital
 15:     { get; set; }
 16: 
 17:     public string BigCity
 18:     { get; set; }
 19: 
 20:     public string NickName
 21:     { get; set; }
 22: }
 23: 
 24: public class StateInfoList : ObservableCollection<StateInfo>
 25: {
 26: }
 27: 

Once we have this class then we can directly use the items soruce property of list box. After that whenever there is any change in the collection, it will automatically reflected in the list box. Here is a piece of code to do the sorting on the collection by name.

  1: lst.Items.SortDescriptions.Clear();
  2: SortDescription sd = new SortDescription("Name", ListSortDirection.Ascending);
  3: lst.Items.SortDescriptions.Add(sd);
  4: 

Here we first clear the existing sorting description if there is any. It is important, because if we don’t do it then we will apply the additional sorting. For example if user first click on the sort by name and then sort by capital then it will not sort by capital but sort by both of them giving state name preference. Therefore it is important to clear the existing sort description to get the desire result.

Here is a complete XAML code of this program.

  1: <Window x:Class="WpfListBox.Window1"
  2:     xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
  3:     xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
  4:     Title="List Box Sample" Height="600" Width="800" Loaded="Window_Loaded">
  5:     <Grid>
  6:         <Grid.RowDefinitions>
  7:             <RowDefinition Height="7*"/>
  8:             <RowDefinition/>
  9:         </Grid.RowDefinitions>
 10:         <Grid.ColumnDefinitions>
 11:             <ColumnDefinition/>
 12:             <ColumnDefinition/>
 13:             <ColumnDefinition/>
 14:             <ColumnDefinition/>
 15:         </Grid.ColumnDefinitions>
 16:         
 17:         <ListBox Grid.Row="0" Grid.ColumnSpan="4" Name="lst" Margin="5" ItemsSource="{Binding}" HorizontalContentAlignment="Stretch">
 18:             <ListBox.ItemTemplate>
 19:                 <DataTemplate>
 20:                     <Border Margin="5" Background="Wheat" BorderThickness="5" BorderBrush="Brown">
 21:                         <StackPanel>
 22:                             <TextBlock Margin="5" FontSize="16" FontWeight="Bold" Text="{Binding Path=Name}"/>
 23:                             <TextBlock Margin="5, 0"  Foreground="Blue" Text="{Binding Path=Capital}"/>
 24:                             <TextBlock Margin="5, 0"  Text="{Binding Path=BigCity}"/>
 25:                             <TextBlock Margin="5" Text="{Binding Path=NickName}"/>
 26:                         </StackPanel>
 27:                     </Border>
 28:                 </DataTemplate>
 29:             </ListBox.ItemTemplate>
 30:         </ListBox>
 31:         <Button Name="sortName" Grid.Column="0" Grid.Row="1" Width="120" Height="35" Click="sortName_Click">
 32:             Sort by Name
 33:         </Button>
 34:         <Button Name="sortCapital" Grid.Column="1" Grid.Row="1" Width="120" Height="35" Click="sortCapital_Click">
 35:             Sort by Capital
 36:         </Button>
 37:         <Button Name="sortBigCity" Grid.Column="2" Grid.Row="1" Width="120" Height="35" Click="sortBigCity_Click">
 38:             Sort by Big City
 39:         </Button>
 40:         <Button Name="sortNick" Grid.Column="3" Grid.Row="1" Width="120" Height="35" Click="sortNick_Click">
 41:             Sort by Nick Name
 42:         </Button>
 43:     </Grid>
 44: </Window>
 45: 

 

And here is complete C# code of the program.

 

  1: using System;
  2: using System.Collections.Generic;
  3: using System.Windows;
  4: using System.Collections.ObjectModel;
  5: using System.ComponentModel;
  6: 
  7: namespace WpfListBox
  8: {
  9:     /// <summary>
 10:     /// Interaction logic for Window1.xaml
 11:     /// </summary>
 12:     public partial class Window1 : Window
 13:     {
 14:         public Window1()
 15:         {
 16:             InitializeComponent();
 17:         }
 18: 
 19:         private void Window_Loaded(object sender, RoutedEventArgs e)
 20:         {
 21:             StateInfoList states = new StateInfoList();
 22: 
 23:             states.Add(new StateInfo("Maryland", "Annapolis", "Baltimore", "Old Line State"));
 24:             states.Add(new StateInfo("California", "Sacramento", "Los Angeles", "Golden State"));
 25:             states.Add(new StateInfo("Washington", "Olympia", "Seattle", "The Evergreen State"));
 26:             states.Add(new StateInfo("Taxes", "Austin", "Houston", "Lone Star State"));            
 27:             states.Add(new StateInfo("New York", "Albany", "New York City", "Empire State"));
 28: 
 29:             lst.ItemsSource = states;
 30:         }
 31: 
 32:         private void sortName_Click(object sender, RoutedEventArgs e)
 33:         {
 34:             lst.Items.SortDescriptions.Clear();
 35:             SortDescription sd = new SortDescription("Name", ListSortDirection.Ascending);
 36:             lst.Items.SortDescriptions.Add(sd);
 37:         }
 38: 
 39:         private void sortCapital_Click(object sender, RoutedEventArgs e)
 40:         {
 41:             lst.Items.SortDescriptions.Clear();
 42:             SortDescription sd = new SortDescription("Capital", ListSortDirection.Ascending);
 43:             lst.Items.SortDescriptions.Add(sd);
 44:         }
 45: 
 46:         private void sortBigCity_Click(object sender, RoutedEventArgs e)
 47:         {
 48:             lst.Items.SortDescriptions.Clear();
 49:             SortDescription sd = new SortDescription("BigCity", ListSortDirection.Ascending);
 50:             lst.Items.SortDescriptions.Add(sd);
 51:         }
 52: 
 53:         private void sortNick_Click(object sender, RoutedEventArgs e)
 54:         {
 55:             lst.Items.SortDescriptions.Clear();
 56:             SortDescription sd = new SortDescription("NickName", ListSortDirection.Ascending);
 57:             lst.Items.SortDescriptions.Add(sd);
 58:         }
 59:     }
 60: 
 61:     public class StateInfo
 62:     {
 63:         public StateInfo(string name, string capital, string bigcity, string nickname)
 64:         {
 65:             Name = name;
 66:             Capital = capital;
 67:             BigCity = bigcity;
 68:             NickName = nickname;
 69:         }
 70: 
 71:         public string Name
 72:         { get; set; }
 73: 
 74:         public string Capital
 75:         { get; set; }
 76: 
 77:         public string BigCity
 78:         { get; set; }
 79: 
 80:         public string NickName
 81:         { get; set; }
 82:     }
 83: 
 84:     public class StateInfoList : ObservableCollection<StateInfo>
 85:     {
 86:     }
 87: 
 88: }
 89: 

 

This would be the output of the program when it runs.

 

WPFSort_01

And here is the output of the program when we click on Sort by name.

 

WPFSort_02

Similarly this is the output when we click sort by capital.

WPFSort_03

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

Categories

%d bloggers like this: