LINQ to SQL with WPF, and ListBox SelectedItem binding


This article covers LINQ to SQL with WPF, and binding the SelectedItem of a ListBox control.

LINQ is a set of technologies introduced in Visual Studio 2008 and enables you to work with data from different data sources present in various data formats. As per the MSDN library, LINQ is "a set of extensions to the .NET Framework that encompass language-integrated query, set, and transform operations. It extends C# and Visual Basic with native language syntax for queries and provides class libraries to take advantage of these capabilities."

Wikipedia has a simpler definition: LINQ is "a Microsoft .NET Framework component that adds native data querying capabilities to .NET languages."

One of the important implementations of LINQ, LINQ to SQL, gives you a runtime infrastructure for managing relational data as objects without losing the ability to perform query operations. LINQ To SQL is one of the approaches in LINQ through which you can bind any LINQ-enabled data source using SQL syntax.

You can bind to data in a WPF application using LINQ To SQL. Let us see how to do this.

This article assumes that you are using SQL Server 2008 and have the sample database Northwind attached to your Oracle instance.

  1. Create a new WPF application named LinqToSql.
  2. Drag and drop a ListBox and a TextBox into the designer view of MainWindow.xaml. Configure their properties 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" >

           </ListBox>

            <TextBox Height="23" HorizontalAlignment="Left" Margin="158,236,0,0" Name="txtName" VerticalAlignment="Top" Width="224" Text="{Binding SelectedItem.FirstName, ElementName=lstNames}" />

            <TextBlock Height="24" HorizontalAlignment="Left" Margin="38,30,0,0" Name="textBlock1" Text="Select an entry:" VerticalAlignment="Top" Width="114" />

        </Grid>

    </Window>
     

  3. Select Project->Add New Item . Select LINQ to SQL Classes as the template. Rename the file as Emp. The extension dbml is automatically added. A dbml file is a database markup language file.

    WPFLinqSQL1.gif

    Figure 1
     
  4. Select Data menu and then select the Add New Data Sources option.

    WPFLinqSQL2.gif

    Figure 2
     
  5. In the Choose Data Source wizard, select Database as shown in Figure 3 and click Next.

    WPFLinqSQL3.gif

    Figure 3
     
  6. In the Choose Database Model section, select DataSet as shown in Figure 4 and click Next.

    WPFLinqSQL4.gif

    Figure 4
     
  7. Specify the connection string details as shown in Figure 5.

    WPFLinqSQL5.gif

    Figure 5
     
  8. Select Employees from the list of tables as shown in Figure 6.

    WPFLinqSQL6.gif

    Figure 6

    The data source is added to the Server Explorer.

    Open the designer area of the Emp.dbml file. Drag the Employees table from the Server Explorer to the designer area. This results in the Employee data class being generated as shown in Figure 7.

    WPFLinqSQL7.gif

    Figure 7

    This also results in the creation of a data context which is named as EmpDataContext. Figure 8 shows the data context created in the .dbml file.

    WPFLinqSQL8.gif

    Figure 8
     
  9. Save the file.
  10. Click Project-> Add Class and add a new class named ObservableEmployee. Add the following code to this class. This creates an ObservableCollection of employees.

            class ObservableEmployee : ObservableCollection<Employee>
            {
                public ObservableEmployee(EmpDataContext edc)
                {
                    foreach (Employee emp in edc.Employees)
                    {
                        this.Add(emp);
                    }
                }
            }

     
  11. Update the XAML markup in MainWindow.xaml to set the ITemTemplate and DataTemplate of the ListBox and set the binding of the TextBox 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>
            <TextBox Height="23" HorizontalAlignment="Left" Margin="158,236,0,0" Name="txtName" VerticalAlignment="Top" Width="224" Text="{Binding SelectedItem.FirstName, ElementName=lstNames}" />
            <TextBlock Height="24" HorizontalAlignment="Left" Margin="38,30,0,0" Name="textBlock1" Text="Select an entry:" VerticalAlignment="Top" Width="114" />
        </Grid>
    </
    Window>

Here, the ListBox template is set such that it is bound to a combination of First Name and Last Name columns in the Employees table of the database. The TextBox in turn is bound to the SelectedItem property of the ListBox so that whenever a user selects an item from the ListBox, the first name is displayed in the TextBox.

However, the binding is not done directly, it is done through the LINQ to SQL class and the ObservableCollection of employees as shown below:

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

        public MainWindow()
        {
            InitializeComponent();
        }

        private void Window_Loaded(object sender, RoutedEventArgs e)
        {
            // Populate the observable collection of employees from the database
            _knownEmp = new ObservableEmployee(_empDC);

            // Set this to the ItemsSource property of the ListBox

            this.lstNames.ItemsSource = _knownEmp;
        }
    }


Save, build, and execute the application. Sample output is shown in Figure

WPFLinqSQL9.gif

Figure 9

Conclusion: This article covered LINQ to SQL with WPF, and binding the SelectedItem of a ListBox control.