Data Binding in WPF DataGrid Control Using SQL Server Database Via LINQ
Introduction
This article explains how to use a DataGrid control in WPF and binding to a DataGrid in a WPF 4.5 application using SQL server as Database.
  • WPF ApplicationFrom
  • DataGrid control
  • SQL SERVER Database
Download The Above SqlServer_Emp.zip file and extract the Emp.Sql from the zip file and open the file and execute in SQL server Management Studio. it will create you the table named "Emp" under "WpfPractice" Database.
Now your Database is Ready...
Next Create a new project using "File" > "New" > "Project..." > "WPF Application" and name it: "DataBindingControls".
Now right click the "DataBindingControls"in solution Explorer and click on Add->New Item-> Choose Language as Visual C# ->Windows and select Window(WPF) and click on Add.
design the DataGridbindData Window by using below controls from the ToolBox.
Now from the Toolbox Select:
  • 1 Grid
  • 1 Text block
  • DataGrid control
  • 1 Button
  • 1 StackPanel
Now design your DataGridbindData.xaml View design part; use the following code:
DataGridbindData.xaml
  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 like below.
Now Add your Database Table into your Application By using ADO.NET Entity Data Model.
right click the "DataBindingControls"in solution Explorer and click on Add->New Item-> Choose Language as Visual C# -> Data ->select ADO.NET Entity Data Model. and click on Add.
from the Choose model contents select Generate from the Database then click on next button
click on new connection from below window
Click on Next
provide the credentials and select data base name as WpfPractice and Click on Ok button
check the tables checkbox and click on finish.
automatically it will write the connection string into your App.config file.
Auto Generated App.Config is as follows:
App.Xaml
  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.
DataGridbindData.xaml.cs
  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. namespace DataBindingControls
  15. {
  16. /// <summary>
  17. /// Interaction logic for DataGridBindData.xaml
  18. /// </summary>
  19. public partial class DataGridBindData : Window
  20. {
  21. public DataGridBindData()
  22. {
  23. InitializeComponent();
  24. }
  25. private void btndisplaydata_Click(object sender, RoutedEventArgs e)
  26. {
  27. try
  28. {
  29. WpfPracticeEntities Con = new WpfPracticeEntities();
  30. List<Emp> TableData = Con.Emps.ToList();
  31. EmpDataGrid.ItemsSource = TableData;
  32. }
  33. catch (Exception ex)
  34. {
  35. MessageBox.Show(ex.ToString());
  36. }
  37. }
  38. }
  39. }
Open Your App.xaml file and and set StartupUri="DataGridbindData.xaml".
Run the application
Now click on Display Data Button. here is the output.
sorry guys i couldn't provide the complete file here only because of size limitation problem.
you can get the complete document from below link
Download DatabindingControls.zip
I hope this article is useful. If you have any other questions then please provide your comments below.