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".
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.
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
Now design your DataGridbindData.xaml View design part use the following code:
- <Window x:Class="DataBindingControls.DataGridBindData"
- xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
- xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
- Title="DataGridBindData" Height="330" Width="490">
- <StackPanel>
- <Grid>
- <Grid.RowDefinitions>
- <RowDefinition Height="41*"/>
- <RowDefinition Height="183*"/>
- <RowDefinition Height="45*"/>
- </Grid.RowDefinitions>
- <TextBlock Text="Employees"
- FontSize="25"
- Foreground="Chocolate"
- Grid.Row="0"
- VerticalAlignment="Top"
- Margin="10,5,0,0"/>
- <DataGrid Name="EmpDataGrid"
- Grid.Row="1"
- AutoGenerateColumns="False"
- Margin="10,5,0,0"
- Height="200"
- Width="450"
- HorizontalAlignment="Left"
- ItemsSource="{Binding Path=LoadDataBinding}"
- CanUserResizeRows="False"
- CanUserAddRows="False">
- <DataGrid.Columns>
- <DataGridTextColumn Header="Empno" Binding="{Binding Path=Empno}" IsReadOnly="True" Width="80"/>
- <DataGridTextColumn Header="name" Binding="{Binding Path=Ename}" IsReadOnly="True" Width="120"/>
- <DataGridTextColumn Header="Job" Binding="{Binding Path=Job}" IsReadOnly="True" Width="100"/>
- <DataGridTextColumn Header="Salary" Binding="{Binding Path=Sal}" IsReadOnly="True" Width="120"/>
- </DataGrid.Columns>
- </DataGrid>
- <Button Name="btndisplaydata"
- Content="Display Data"
- HorizontalAlignment="Left"
- VerticalAlignment="Top"
- Grid.Row="2"
- Margin="320,5,10,3"
- Height="35"
- Width="140"
- FontSize="20"
- Click="btndisplaydata_Click"/>
- </Grid>
- </StackPanel>
- </Window>
You will get the DataGridbindData.xaml window form.
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.
From the choose model contents select
Generate from the Database then click on the "Next >" button.
Click on
New connection.
Provide the credentials and select the database name as
WpfPractice and click on the Ok button.
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:
- <?xml version="1.0" encoding="utf-8"?>
- <configuration>
- <configSections>
-
- <section name="entityFramework" type="System.Data.Entity.Internal.ConfigFile.EntityFrameworkSection, EntityFramework, Version=6.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" requirePermission="false" />
- </configSections>
- <startup>
- <supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.5" />
- </startup>
- <connectionStrings>
- <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" />
- </connectionStrings>
- <entityFramework>
- <defaultConnectionFactory type="System.Data.Entity.Infrastructure.SqlConnectionFactory, EntityFramework" />
- <providers>
- <provider invariantName="System.Data.SqlClient" type="System.Data.Entity.SqlServer.SqlProviderServices, EntityFramework.SqlServer" />
- </providers>
- </entityFramework>
- </configuration>
Now, in the code behind file “DataGridbindData.xaml.cs“ use the following code.
- 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.Shapes;
-
- namespace DataBindingControls
- {
- public partial class DataGridBindData : Window
- {
- public DataGridBindData()
- {
- InitializeComponent();
- }
-
- private void btndisplaydata_Click(object sender, RoutedEventArgs e)
- {
- try
- {
- WpfPracticeEntities Con = new WpfPracticeEntities();
- List<Emp> TableData = Con.Emps.ToList();
- EmpDataGrid.ItemsSource = TableData;
- }
- catch (Exception ex)
- {
- MessageBox.Show(ex.ToString());
- }
- }
- }
- }
Open Your
App.xaml file and and set
StartupUri="DataGridbindData.xaml".
Run the application:
Now click on the
Display Data Button. Here is the output.
I hope this article is useful. If you have any other questions then please provide your comments below.