Introduction
This article shows how to select data using LINQ to SQL in WPF applications.
Create a WPF application as in Figure 1.
Figure 1: Create WPF application
Add LINQ to SQL classes to the project as in Figures 2 and 3.
Figure 2: Add LINQ to SQL
Figure 3: Choose database objects
MainWindow.xaml
- <Window x:Class="SelectData_WPF_LINQtoSQL.MainWindow"
- xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
- xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
- Title="MainWindow"
- Width="525"
- Height="350"
- Loaded="Window_Loaded">
- <Grid>
- <DataGrid x:Name="dgEmployee"
- Width="267"
- Margin="118,47,0,0"
- HorizontalAlignment="Left"
- VerticalAlignment="Top"
- AutoGenerateColumns="False"
- CanUserAddRows="False"
- ColumnWidth="*">
- <DataGrid.Columns>
- <DataGridTextColumn x:Name="dgrEmpId"
- Binding="{Binding EmpId}"
- Header="EmpId"
- IsReadOnly="True" />
- <DataGridTextColumn x:Name="dgrFirstName"
- Binding="{Binding FirstName}"
- Header="FirstName"
- IsReadOnly="True" />
- <DataGridTextColumn x:Name="dgrLastName"
- Binding="{Binding LastName}"
- Header="LastName"
- IsReadOnly="True" />
- </DataGrid.Columns>
- </DataGrid>
- </Grid>
- </Window>
MainWindow.xaml.cs
- using System;
- using System.Collections.Generic;
- using System.Linq;
- using System.Text;
- using System.Threading.Tasks;
- using System.Windows;
- using System.Windows.Controls;
- using System.Windows.Data;
- using System.Windows.Documents;
- using System.Windows.Input;
- using System.Windows.Media;
- using System.Windows.Media.Imaging;
- using System.Windows.Navigation;
- using System.Windows.Shapes;
-
- namespace SelectData_WPF_LINQtoSQL
- {
-
-
-
- public partial class MainWindow : Window
- {
- public MainWindow()
- {
- InitializeComponent();
- }
-
- private void Window_Loaded(object sender, RoutedEventArgs e)
- {
- dgEmployee.ItemsSource = objContext.Employees.ToList();
- }
-
- DataClasses1DataContext objContext = new DataClasses1DataContext();
- }
- }
The output of the application is as in Figure 4.
Figure 4: Output of the application
Summary
In this article we saw how to select data using LINQ to SQL in WPF applications.