SIGN UP MEMBER LOGIN:    
ARTICLE

Filtering and Sorting a WPF ListBox

Posted by Mamta M Articles | WPF with C# November 24, 2011
This article shows how to filter and sort data in a WPF ListBox.
Reader Level:

This article shows how to filter and sort data in a WPF ListBox.

In the previous article, LINQ to SQL with WPF, and ListBox SelectedItem binding, you saw how to use LINQ to SQL with WPF, and bind the SelectedItem of a ListBox control. This article builds on the same source application and further adds more functionality to it.

Filtering Data

Remove the TextBox created in the previous example and add a new TextBox and a Button control. This TextBox will contain the filter criteria. On click of the Button, the filter operation takes place and the ListBox will display only that data which satisfies the filter condition. The XAML should be as follows:

<Window x:Class="LinqToSql.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
Title="MainWindow" Height="350" Width="525" Loaded="Window_Loaded">
<Grid>
<
ListBox Name="lstNames" Background="BlanchedAlmond" Margin="158,20,144,183" SelectedItem="{Binding FirstName}">
<ListBox.ItemTemplate>
<
DataTemplate>
<
StackPanel Orientation="Horizontal">
<TextBlock Name="FirstName" Width="100" Text="{Binding Path=FirstName}"></TextBlock>
<TextBlock Name="LastName" Width="100" Text="{Binding Path=LastName}"></TextBlock>
</StackPanel>
</
DataTemplate>
</
ListBox.ItemTemplate>
</
ListBox>
<
TextBlock Height="23" HorizontalAlignment="Left" Margin="38,145,0,0" Name="textBlock1" Text="Type Employee Name:" VerticalAlignment="Top" Width="114" />
<TextBox Name="txtSearch" Height="23" HorizontalAlignment="Right" Margin="0,145,144,0" VerticalAlignment="Top" Width="201" />
<Button Content="Filter" Height="23" HorizontalAlignment="Left" Margin="284,196,0,0" Name="button1" VerticalAlignment="Top" Width="75" Click="button1_Click" />
<TextBlock Height="24" HorizontalAlignment="Left" Margin="38,30,0,0" Name="textBlock2" Text="Select an entry:" VerticalAlignment="Top" Width="114"
/>
</Grid>
</
Window>

The code-behind class contains the logic to perform the filtering operation.

public partial class MainWindow : Window
    {
        private static EmpDataContext _dataDC = new EmpDataContext();
        private ObservableEmployee _knownEmp;

        public MainWindow()
        {
            InitializeComponent();
        }

        private void Window_Loaded(object sender, RoutedEventArgs e)
        {
            knownEmp = new ObservableEmployee(_dataDC);
            this.lstNames.ItemsSource = _knownEmp;
        }

        private void button1_Click(object sender, RoutedEventArgs e)
        {
            string searchText = txtSearch.Text;

            lstNames.Items.Filter = delegate(object obj)
            {
                Employee emp = (Employee)obj;
                string str = emp.FirstName.ToString();
                if (String.IsNullOrEmpty(str)) return false;
                int index = str.IndexOf(searchText, 0);

                return (index > -1);
            };
        }
    }
}


Instead of using an anonymous delegate as shown in the above code, you could also use a lambda expression if you are familiar with it.

The outcome of the application is shown below:

WPFListBox1.gif

Figure 1

On typing the name Steven, and clicking Filter, the output is as follows:

WPFListBox2.gif

Figure 2

Sorting Data

Similarly you can sort the data in a particular order. The SortDescription structure enables you to perform a sort operation by specifying a property name and a sort direction. The below snippet adds a SortDescription to sort data based on name in ascending order.

lstNames.Items.SortDescriptions.Add(new SortDescription("FirstName", ListSortDirection.Ascending));
To use the ListSortDirection class, you must reference the System.ComponentModel namespace as follows:

using System.ComponentModel;

Add the following markup to the XAML file:

<Button Content="Sort" Height="23" HorizontalAlignment="Left" Margin="300,193,0,0" Name="button2" VerticalAlignment="Top" Width="75" Click="button2_Click" />

In the code-behind, you will add the following code:

private void button2_Click(object sender, RoutedEventArgs e)
{
    lstNames.Items.SortDescriptions.Add(new SortDescription("FirstName",                 
                                  ListSortDirection.Ascending));        

}

The output after clicking Sort is as follows:

WPFListBox3.gif

Figure 3

Conclusion: This article covered filtering and sorting in a WPF ListBox control.
 

Login to add your contents and source code to this article
share this article :
post comment
 

nice example

Posted by Paras Paras May 05, 2012
Team Foundation Server Hosting
Become a Sponsor
PREMIUM SPONSORS
  • Finally – a virtual platform that delivers next-generation Windows Server 2008 Hyper-V virtualization technology from a managed hosting partner you can truly depend on. Visit www.maximumasp.com/max for a FREE 30 day trial. Hurry offer ends soon. Climb aboard the MaxV platform and take advantage of High Availability, Intelligent Monitoring, Recurrent Backups, and Scalability – with no hassle or hidden fees. As a managed hosting partner focused solely on Microsoft technologies since 2000, MaximumASP is uniquely qualified to provide the superior support that our business is built on. Unparalleled expertise with Microsoft technologies lead to working directly with Microsoft as first to offer IIS 7 and SQL 2008 betas in a hosted environment; partnering in the Go Live Program for Hyper-V; and product co-launches built on WS 2008 with Hyper-V technology.
    ceTE software specializes in components for dynamic PDF generation and manipulation. The DynamicPDF™ product line allows you to dynamically generate PDF documents, merge PDF documents and new content to existing PDF documents from within your applications.
Team Foundation Server Hosting
Become a Sponsor