Posted by: Zeeshan Amjad | July 22, 2009

Using LINQ in WPF Application for Data Binding


User interface control in WPF can also be bind with the result set return using LINQ (Language Integrated Query). Let’s take a look at very simple example where data returned by the LINQ is bind with the WPF control.

In this example we are going to make one very simple class for student that store some very basic information about the student such as student id, first name, last name and final grade. Here is the simple implementation of this class.

  1:     public class Student
  2:     {
  3:         public Student(int id, 
  4:             String firstName, 
  5:             String lastName,
  6:             String grade)
  7:         {
  8:             ID = id;
  9:             FirstName = firstName;
 10:             LastName = lastName;
 11:             Grade = grade;
 12:         }
 13: 
 14:         public int ID
 15:         { get; set; }
 16: 
 17:         public String FirstName
 18:         { get; set; }
 19: 
 20:         public String LastName
 21:         { get; set; }
 22: 
 23:         public String Grade
 24:         { get; set; }
 25:     }
 26: 

 

Now we are going to make an array of this class. For simplicity here we store some student’s records at the time of deceleration, but it is not a constraint. We can populate this array with stream, XML file, database or any other sources. Here is the code to fill few records in this array.

  1:         Student[] studentClass = { new Student(5, "Bob", "Smith", "Passed"),
  2:                 new Student(10, "Alex", "Martin", "Passed"),
  3:                 new Student(12, "Joe", "Brown" , "Failed"),
  4:                 new Student(13, "Ralph", "Ronald" , "Failed"),
  5:                 new Student(16, "David", "Frank", "Passed"),
  6:                 new Student(18, "Patrick", "Justin", "Failed"),
  7:                 new Student(22, "Roy", "Williams", "Failed"),
  8:                 new Student(25, "Ken", "White", "Passed")};
  9: 

We explicitly made few records for passed students and few for fail students. Now if we want to filter only those students whose grade is passed then we can do it with this very simple LINQ query.

  1:             IEnumerable<Student> selectedStudents = from fn in studentClass
  2:                                          where fn.Grade == "Passed"
  3:                                          select fn;
  4: 

“selectedStudents” has a enumerable of student type that contains only those students whose grade is passed. That was the LINQ part of the solution; now take a look at the WPF stuff. We created two list view in a grid to display all students and passed students. Here is the simple XAML file to do this.

  1: <Window x:Class="LINQWPF.Main"
  2:     xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
  3:     xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
  4:     Title="LINQ and WPF" Height="400" Width="400" Loaded="Window_Loaded">
  5:     <Grid>
  6:         
  7:         <Grid.RowDefinitions>
  8:             <RowDefinition Height="4*"/>
  9:             <RowDefinition/>
 10:         </Grid.RowDefinitions>
 11:         
 12:         <Grid.ColumnDefinitions>
 13:             <ColumnDefinition/>
 14:             <ColumnDefinition/>
 15:         </Grid.ColumnDefinitions>
 16:         
 17:         <StackPanel Grid.Row="0" Grid.Column="0">
 18:             <TextBlock Margin="5,5" FontSize="20" TextAlignment="Center">
 19:                 <TextBlock.Background>
 20:                     <LinearGradientBrush>
 21:                         <GradientStop Color="Wheat" Offset="0"/>
 22:                         <GradientStop Color="Salmon" Offset="1"/>
 23:                     </LinearGradientBrush>
 24:                 </TextBlock.Background>                
 25:                 All Students
 26:             </TextBlock>
 27:             
 28:             <ListView Margin="5,5" Name="lstAllItems" Grid.Row="0" Grid.Column="0">
 29:                 <ListView.View>
 30:                     <GridView>
 31:                         <GridViewColumn Width="25" Header="ID" DisplayMemberBinding="{Binding Path = ID}"></GridViewColumn>
 32:                         <GridViewColumn Width="80" Header="First Name" DisplayMemberBinding="{Binding Path = FirstName}"></GridViewColumn>
 33:                         <GridViewColumn Width="80" Header="Last Name" DisplayMemberBinding="{Binding Path = LastName}"></GridViewColumn>
 34:                     </GridView>
 35:                 </ListView.View>            
 36:             </ListView>
 37:         </StackPanel>            
 38:         
 39:         <StackPanel Grid.Row="0" Grid.Column="1">
 40:             <TextBlock Margin="5,5" FontSize="20" TextAlignment="Center">
 41:                 <TextBlock.Background>
 42:                     <LinearGradientBrush>
 43:                         <GradientStop Color="Wheat" Offset="0"/>
 44:                         <GradientStop Color="Salmon" Offset="1"/>
 45:                     </LinearGradientBrush>
 46:                 </TextBlock.Background>
 47:                 Pass Students
 48:             </TextBlock>
 49:             <ListView Margin="5,5" Name="lstSelectedItems" Grid.Row="0" Grid.Column="1">
 50:                 <ListView.View>
 51:                     <GridView>
 52:                         <GridViewColumn Width="25" Header="ID" DisplayMemberBinding="{Binding Path = ID}"></GridViewColumn>
 53:                         <GridViewColumn Width="80" Header="First Name" DisplayMemberBinding="{Binding Path = FirstName}"></GridViewColumn>
 54:                         <GridViewColumn Width="80" Header="Last Name" DisplayMemberBinding="{Binding Path = LastName}"></GridViewColumn>
 55:                     </GridView>
 56:                 </ListView.View>
 57:             </ListView>
 58:         </StackPanel>
 59:         
 60:         <Button Margin="15,15" Name="btnAllItems" Grid.Row="1" Grid.Column="0" Click="btnAllItems_Click">
 61:             Fill All Items
 62:         </Button>
 63:         
 64:         <Button Margin="15, 15" Name="btnSelectedItems" Grid.Row="1" Grid.Column="1" Click="btnSelectedItems_Click">
 65:             Fill Selected Items
 66:         </Button>
 67:     </Grid>
 68: </Window>
 69: 

Also note the data binding here is exactly the same as if we are not using LINQ. LINQ is used here to get the record set from a whole data set that fulfills the given requirement. In Select all button handler we added all the dataset into the list control.

  1:             lstAllItems.Items.Clear();
  2: 
  3:             foreach (Student student in studentClass)
  4:             {
  5:                 lstAllItems.Items.Add(student);
  6:             }
  7: 

And in the handler of selected students button we display the enumerable type records we get back from the LINQ.

Here is the complete code of whole program.

  1: using System;
  2: using System.Collections.Generic;
  3: using System.Linq;
  4: using System.Windows;
  5: using System.Windows.Controls;
  6: 
  7: namespace LINQWPF
  8: {
  9:     /// <summary>
 10:     /// Interaction logic for Main.xaml
 11:     /// </summary>
 12:     public partial class Main : Window
 13:     {
 14:         Student[] studentClass = { new Student(5, "Bob", "Smith", "Passed"),
 15:                 new Student(10, "Alex", "Martin", "Passed"),
 16:                 new Student(12, "Joe", "Brown" , "Failed"),
 17:                 new Student(13, "Ralph", "Ronald" , "Failed"),
 18:                 new Student(16, "David", "Frank", "Passed"),
 19:                 new Student(18, "Patrick", "Justin", "Failed"),
 20:                 new Student(22, "Roy", "Williams", "Failed"),
 21:                 new Student(25, "Ken", "White", "Passed")};
 22: 
 23:         public Main()
 24:         {
 25:             InitializeComponent();
 26:         }
 27: 
 28:         private void Window_Loaded(object sender, RoutedEventArgs e)
 29:         {
 30:             btnSelectedItems.IsEnabled = false;
 31:         }
 32: 
 33:         private void btnAllItems_Click(object sender, RoutedEventArgs e)
 34:         {
 35:             lstAllItems.Items.Clear();
 36: 
 37:             foreach (Student student in studentClass)
 38:             {
 39:                 lstAllItems.Items.Add(student);
 40:             }
 41: 
 42:             btnSelectedItems.IsEnabled = true;
 43:         }
 44: 
 45:         private void btnSelectedItems_Click(object sender, RoutedEventArgs e)
 46:         {
 47:             lstSelectedItems.Items.Clear();
 48: 
 49:             IEnumerable<Student> selectedStudents = from fn in studentClass
 50:                                          where fn.Grade == "Passed"
 51:                                          select fn;
 52: 
 53:             foreach (Student student in selectedStudents)
 54:             {
 55:                 lstSelectedItems.Items.Add(student);
 56:             }
 57:         }
 58:     }
 59: 
 60:     public class Student
 61:     {
 62:         public Student(int id, 
 63:             String firstName, 
 64:             String lastName,
 65:             String grade)
 66:         {
 67:             ID = id;
 68:             FirstName = firstName;
 69:             LastName = lastName;
 70:             Grade = grade;
 71:         }
 72: 
 73:         public int ID
 74:         { get; set; }
 75: 
 76:         public String FirstName
 77:         { get; set; }
 78: 
 79:         public String LastName
 80:         { get; set; }
 81: 
 82:         public String Grade
 83:         { get; set; }
 84:     }
 85: }
 86: 

And here is the output of the program.

LINQWPF

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: