WPF Bind DataGrid using SQL Database

wpf datagrid from database

In this post we will Bind our WPF DataGrid control from MS SQL Database. WPF Datagrid bind sql database. Fill WPF Datagrid from MS SQL Database.

WPF Datagrid control Binding from MS SQL Database Code :

String connectionString = "Data Source=192.168.0.192;Initial Catalog=ParallelCodes;User ID=sa;Password=789";
SqlConnection con = new SqlConnection(connectionString);
SqlCommand cmd = new SqlCommand("select * from Producttbl", con);
con.Open();
SqlDataAdapter adapter = new SqlDataAdapter(cmd);
DataTable dt = new DataTable();
adapter.Fill(dt);
myDataGrid.ItemsSource = dt.DefaultView;
cmd.Dispose();
con.Close();

datagridID.ItemsSource = DataTableName.DefaultView will fill up WPF Datagrid from MS SQL Database in the above code.

wpf datagrid from database

WPF Datagrid using MS SQL Server Database – Output Image 01

Usage :

WPF xaml page :

<Window x:Class="WPFParallelCodes.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
Title="MainWindow" Height="350" Width="525" WindowState="Maximized">
<StackPanel Orientation="Vertical" HorizontalAlignment="Left" Width="Auto" Height="Auto">
<Button Name="btnFill" Content="Fill Data" MaxWidth="200" Margin="5" Click="btnFill_Click_1"/>
<DataGrid Name="myDataGrid"/>
</StackPanel>
</Window>

WPF Code Page :

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
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;
using System.Data;
using System.Data.SqlClient;

namespace WPFParallelCodes
{
/// <summary>
/// Interaction logic for MainWindow.xaml
/// </summary>
public partial class MainWindow : Window
{
public MainWindow()
{
InitializeComponent();
}

private void btnFill_Click_1(object sender, RoutedEventArgs e)
{
try
{
String connectionString = "Data Source=192.168.0.192;Initial Catalog=ParallelCodes;User ID=sa;Password=789";
SqlConnection con = new SqlConnection(connectionString);
SqlCommand cmd = new SqlCommand("select * from Producttbl", con);
con.Open();
SqlDataAdapter adapter = new SqlDataAdapter(cmd);
DataTable dt = new DataTable();
adapter.Fill(dt);
myDataGrid.ItemsSource = dt.DefaultView;
cmd.Dispose();
con.Close();
}
catch (Exception ex)
{
}
}
}
}

Result :

wpf datagrid from database

WPF Datagrid using MS SQL Server Database – Output Image 01

See Also :


  1. Base64Encode.io - Realtime Encode your string to Base64 format.
  2. Base64Decode.io - Realtime Decode Base64 data to plain text.
  3. Md5Hash.io - Realtime Encoding in Md5Hash.

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.