DataGrid in WPF:
How to bind records in DataGrid using WPF?
MainWindow.xaml:
<Window x:Class="DataGridInWPF.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
Title="MainWindow" Height="250" Width="550" Loaded="Window_Loaded">
<Grid>
<DataGrid HorizontalAlignment="Center" Name="dataGrid1"
AutoGenerateColumns="False"
CanUserResizeRows="True"
CanUserResizeColumns="True"
CanUserReorderColumns="True">
<DataGrid.Columns>
<DataGridTextColumn Binding="{Binding Path=CustomerID}" Header="ID" MaxWidth="50" />
<DataGridTextColumn Binding="{Binding Path=CompanyName}" Header="Company" MaxWidth="100" />
<DataGridTextColumn Binding="{Binding Path=ContactName}" Header="Name" MaxWidth="100" />
<DataGridTextColumn Binding="{Binding Path=City}" Header="City" MaxWidth="100" />
<DataGridTextColumn Binding="{Binding Path=Country}" Header="Country" MaxWidth="100" />
<DataGridTextColumn Binding="{Binding Path=Phone}" Header="Phone" MaxWidth="100" />
</DataGrid.Columns>
</DataGrid>
</Grid>
</Window>
Figure 1: Display DatGrid in design format.
MainWindow.xaml.cs:
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 DataGridInWPF
{
/// <summary>
/// Interaction logic for MainWindow.xaml
/// </summary>
public partial class MainWindow : Window
{
SqlConnection MyConnection;
SqlCommand MyCommand;
SqlDataAdapter MyAdapter;
DataTable MyTable;
public MainWindow()
{
InitializeComponent();
}
private void Window_Loaded(object sender, RoutedEventArgs e)
{
BindGrid();
}
private void BindGrid()
{
MyConnection = new SqlConnection();
MyConnection.ConnectionString = "SERVER=Puru;Uid=sa; pwd=wintellect;Database=TestData;";
if (MyConnection.State == ConnectionState.Closed)
MyConnection.Open();
MyCommand = new SqlCommand();
MyCommand.CommandText = "Select CustomerID,CompanyName,ContactName,Country,City,Phone from CustomerDetail";
MyCommand.CommandType = CommandType.Text;
MyCommand.Connection = MyConnection;
MyTable = new DataTable();
MyAdapter = new SqlDataAdapter();
MyAdapter.SelectCommand = MyCommand;
MyAdapter.Fill(MyTable);
dataGrid1.ItemsSource = MyTable.DefaultView;
}
}
}