Data Binding in WPF DataGrid Control Using MySQL Database

Introduction

 
This article explains how to use a DataGrid control in WPF and binding to a DataGrid in a WPF 4.5 application.
  • WPF ApplicationFrom
  • DataGrid control
  • MySQL Database
See the following screen; select "MySQL Wamp Server database" > "customers data".
 
 
Create a new project using "File" > "New" > "Project..." > "WPF Application" and name it: "DataGridBind".
 
 
Now from the Toolbox Select:
  • 1 Grid
  • 1 Text block
  • DataGrid control
  • 1 Button
 
You will get the MainWindow.xaml window form.
 
 
Now design your MainWindow.xaml View design part; use the following code:
  1. <Window x:Class="DataGridBind.MainWindow" xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" Title="MainWindow" Height="350" Width="620">  
  2.      <Grid Height="350" Width="625" Background="#FFD1F9EE">  
  3.           <TextBlock Height="32" HorizontalAlignment="Left" Margin="16,15,0,0" Name="textBlockHeading" Text="Customers" VerticalAlignment="Top" Width="310" FontSize="20" FontStretch="Normal" />  
  4.           <Grid HorizontalAlignment="Left" Height="310" VerticalAlignment="Top" Width="625">  
  5.                <DataGrid AutoGenerateColumns="False" HorizontalAlignment="Left" Margin="14,55,0,46" Name="dataGridCustomers" Width="575" ItemsSource="{Binding Path=LoadDataBinding}" CanUserResizeRows="False">  
  6.                     <DataGrid.Columns>  
  7.                          <DataGridTextColumn Binding="{Binding Path=CustomerID}" Header="CustomerID" Width="100" IsReadOnly="True" />  
  8.                          <DataGridTextColumn Binding="{Binding Path=ContactName}" Header="Name" Width="100" IsReadOnly="True" />  
  9.                          <DataGridTextColumn Binding="{Binding Path=Address}" Header="Address" Width="150" IsReadOnly="True" />  
  10.                          <DataGridTextColumn Binding="{Binding Path=City}" Header="City" Width="100" IsReadOnly="True" />  
  11.                          <DataGridTextColumn Binding="{Binding Path=Phone}" Header="Phone" Width="120" IsReadOnly="True" />  
  12.                     </DataGrid.Columns>  
  13.                </DataGrid>  
  14.                <Button Content="Load Data" Height="25" HorizontalAlignment="Left" Margin="487,275,0,0" Name="btnloaddata" VerticalAlignment="Top" Width="100" Click="btnloaddata_Click" />  
  15.           </Grid>  
  16.      </Grid>  
  17. </Window> 
     
In the App.config file create the database connection string as:
  1. <?xml version="1.0" encoding="utf-8" ?>  
  2. <configuration>  
  3.      <connectionStrings>  
  4.           <add name="connectionString" connectionString="Server=localhost;userid=root;password=;Database=northwind" providerName="MySql.Data.MySqlClient" />  
  5.      </connectionStrings>  
  6.      <startup>  
  7.           <supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.5" />  
  8.      </startup>  
  9. </configuration> 
Now, in the code-behind file “MainWindow.xaml.cs“ use the following code.
 
MainWindow.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.Navigation;  
  14. using System.Windows.Shapes;  
  15.   
  16. //Using namespaces  
  17. using System.Data;  
  18. using MySql.Data.MySqlClient;  
  19. using System.Configuration;  
  20.   
  21. namespace DataGridBind {  
  22.     /// <summary>  
  23.     /// Interaction logic for MainWindow.xaml  
  24.     /// </summary>  
  25.     public partial class MainWindow: Window {  
  26.         #region MySqlConnection Connection  
  27.         MySqlConnection conn = new  
  28.         MySqlConnection(ConfigurationManager.ConnectionStrings["ConnectionString"].ConnectionString);  
  29.         public MainWindow() {  
  30.             InitializeComponent();  
  31.         }  
  32.         #endregion  
  33.         #region bind data to DataGrid.  
  34.         private void btnloaddata_Click(object sender, RoutedEventArgs e) {  
  35.             try {  
  36.                 conn.Open();  
  37.                 MySqlCommand cmd = new MySqlCommand("Select CustomerID,ContactName,Address,City,Phone,Email from customers", conn);  
  38.                 MySqlDataAdapter adp = new MySqlDataAdapter(cmd);  
  39.                 DataSet ds = new DataSet();  
  40.                 adp.Fill(ds, "LoadDataBinding");  
  41.                 dataGridCustomers.DataContext = ds;  
  42.             } catch (MySqlException ex) {  
  43.                 MessageBox.Show(ex.ToString());  
  44.             }  
  45.             Finally {  
  46.                 conn.Close();  
  47.             }  
  48.         }  
  49.         #endregion  
  50.     }  
Run the application and select “Customer Window Show”.
 
 
Use the following for “btnloaddata_Click"; bind the Data Grid with the Customer data.
 
 
Now bind the DataGrid in the WPF 4.5 application using a MySQL Database. I hope this article is useful. If you have any other questions then please provide your comments below.