Data Binding in WPF DataGrid Control Using SQL Server Database Via LINQ

This article explains how to use a DataGrid control in WPF and bind to a DataGrid in a WPF 4.5 application using SQL Server as the database.

Introduction

This article explains how to use a DataGrid control in WPF and bind to a DataGrid in a WPF 4.5 application using SQL Server as the database.

  • WPF ApplicationFrom
  • DataGrid control
  • SQL Server Database

Download the preceding SqlServer_Emp.zip file and extract the Emp.Sql from the Zip file and open the file and execute the command in SQL Server Management Studio. It will create the table named "Emp" in the "WpfPractice" database.

Now your Database is Ready

Next
create a new project using "File" > "New" > "Project..." > "WPF Application" and name it: "DataBindingControls".

databind controls

Now right-click the "DataBindingControls" in Solution Explorer and click on Add -> New Item then choose the Language as Visual C# then select Window (WPF) and click on Add.

window wpf

Design the DataGridbindData window using the following controls from the ToolBox.

Now from the Toolbox select:

  • 1 Grid
  • 1 Text block
  • DataGrid control
  • 1 Button
  • 1 StackPanel

    common wpf controls
Now design your DataGridbindData.xaml View design part use the following code:
  1. <Window x:Class="DataBindingControls.DataGridBindData"    
  2. xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"    
  3. xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"    
  4. Title="DataGridBindData" Height="330" Width="490">    
  5. <StackPanel>    
  6. <Grid>    
  7. <Grid.RowDefinitions>    
  8. <RowDefinition Height="41*"/>    
  9. <RowDefinition Height="183*"/>    
  10. <RowDefinition Height="45*"/>    
  11. </Grid.RowDefinitions>    
  12. <TextBlock Text="Employees"    
  13. FontSize="25"    
  14. Foreground="Chocolate"    
  15. Grid.Row="0"    
  16. VerticalAlignment="Top"    
  17. Margin="10,5,0,0"/>    
  18. <DataGrid Name="EmpDataGrid"    
  19. Grid.Row="1"    
  20. AutoGenerateColumns="False"    
  21. Margin="10,5,0,0"    
  22. Height="200"    
  23. Width="450"    
  24. HorizontalAlignment="Left"    
  25. ItemsSource="{Binding Path=LoadDataBinding}"    
  26. CanUserResizeRows="False"    
  27. CanUserAddRows="False">    
  28. <DataGrid.Columns>    
  29. <DataGridTextColumn Header="Empno" Binding="{Binding Path=Empno}" IsReadOnly="True" Width="80"/>    
  30. <DataGridTextColumn Header="name" Binding="{Binding Path=Ename}" IsReadOnly="True" Width="120"/>    
  31. <DataGridTextColumn Header="Job" Binding="{Binding Path=Job}" IsReadOnly="True" Width="100"/>    
  32. <DataGridTextColumn Header="Salary" Binding="{Binding Path=Sal}" IsReadOnly="True" Width="120"/>    
  33. </DataGrid.Columns>    
  34. </DataGrid>    
  35. <Button Name="btndisplaydata"    
  36. Content="Display Data"    
  37. HorizontalAlignment="Left"    
  38. VerticalAlignment="Top"    
  39. Grid.Row="2"    
  40. Margin="320,5,10,3"    
  41. Height="35"    
  42. Width="140"    
  43. FontSize="20"    
  44. Click="btndisplaydata_Click"/>    
  45. </Grid>    
  46. </StackPanel>    
  47. </Window>   
You will get the DataGridbindData.xaml window form.

Cdata grid Bind Data

Now add your database table into your application using an ADO.NET Entity Data Model.

Right-click the "DataBindingControls"in Solution Explorer and click on Add -> New Item then choose the Language as Visual C# then select Data then select ADO.NET Entity Data Model and click on Add.

empty data model

From the choose model contents select Generate from the Database then click on the "Next >" button.

choose Model Contents

Click on New connection.

new connection

Provide the credentials and select the database name as WpfPractice and click on the Ok button.

choose your database object and setting

Check the tables checkbox and click on Finish.

Automatically it will write the connection string into your App.config file.

The auto-generated App.Config is as follows:
  1. <?xml version="1.0" encoding="utf-8"?>    
  2. <configuration>    
  3.   <configSections>    
  4.     <!-- For more information on Entity Framework configuration, visit http://go.microsoft.com/fwlink/?LinkID=237468 -->    
  5.     <section name="entityFramework" type="System.Data.Entity.Internal.ConfigFile.EntityFrameworkSection, EntityFramework, Version=6.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" requirePermission="false" />    
  6.   </configSections>    
  7.   <startup>    
  8.     <supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.5" />    
  9.   </startup>    
  10.   <connectionStrings>    
  11.     <add name="WpfPracticeEntities" connectionString="metadata=res://*/Model1.csdl|res://*/Model1.ssdl|res://*/Model1.msl;provider=System.Data.SqlClient;provider connection string="data source=.;initial catalog=WpfPractice;user id=sa;word=Test123!;MultipleActiveResultSets=True;App=EntityFramework"" providerName="System.Data.EntityClient" />    
  12.   </connectionStrings>     
  13.   <entityFramework>    
  14.     <defaultConnectionFactory type="System.Data.Entity.Infrastructure.SqlConnectionFactory, EntityFramework" />    
  15.     <providers>    
  16.       <provider invariantName="System.Data.SqlClient" type="System.Data.Entity.SqlServer.SqlProviderServices, EntityFramework.SqlServer" />    
  17.     </providers>    
  18.   </entityFramework>    
  19. </configuration>    
Now, in the code behind file “DataGridbindData.xaml.cs“ use the following code.
  1. using System;    
  2. using System.Collections.Generic;    
  3. using System.Linq;    
  4. using System.Text;    
  5. using System.Threading.Tasks;    
  6. using System.Windows;    
  7. using System.Windows.Controls;    
  8. using System.Windows.Data;    
  9. using System.Windows.Documents;    
  10. using System.Windows.Input;    
  11. using System.Windows.Media;    
  12. using System.Windows.Media.Imaging;    
  13. using System.Windows.Shapes;    
  14.     
  15. namespace DataBindingControls    
  16. {   
  17.     public partial class DataGridBindData : Window    
  18.     {    
  19.         public DataGridBindData()    
  20.         {    
  21.             InitializeComponent();    
  22.         }    
  23.     
  24.         private void btndisplaydata_Click(object sender, RoutedEventArgs e)    
  25.         {    
  26.             try   
  27.             {      
  28.             WpfPracticeEntities Con = new WpfPracticeEntities();    
  29.             List<Emp> TableData = Con.Emps.ToList();    
  30.             EmpDataGrid.ItemsSource = TableData;    
  31.              }    
  32.             catch (Exception ex)    
  33.             {    
  34.                 MessageBox.Show(ex.ToString());    
  35.             }    
  36.         }    
  37.     }    
  38. }    
Open Your App.xaml file and and set StartupUri="DataGridbindData.xaml".

Run the application:

display data

Now click on the Display Data Button. Here is the output.

show data


I hope this article is useful. If you have any other questions then please provide your comments below.