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.
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 :
See Also :
- WPF – DataGrid with Buttons and its Clicking method – Get Row Data with WPF DataGrid Buttons
- WPF – Using DataGrid Row MouseDoubleClick for getting row Data – Example
- WPF – Designing Material Design Tabs in WPF using Dragablz
- WPF – Bind ComboBox using MS SQL database
- WPF Textbox with Rounded Corners
- WPF Textbox changing Focus Style Background Colors.