In this article I am going to show how we can connect
our WPF application with Data Base. Here I am binding a List Box with DB. I am
showing Id, Name, Email, City in a List Box.
Below is my XAML code:
<Window x:Class="DataBindingInWPF.Window1"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
Title="Data binding In WPF" Height="423" Width="368" Loaded="Window_Loaded">
<Grid>
<ListBox Margin="73,10,29,10" ItemsSource="{Binding Path=EMP}" Name="lstEmployee">
<ListBox.ItemTemplate>
<DataTemplate>
<StackPanel>
<TextBlock Text="{Binding Path=ID}" />
<TextBlock Text="{Binding Path=Name}" />
<TextBlock Text="{Binding Path=Email}" />
<TextBlock Text="{Binding Path=City}" />
<TextBlock Text="--------------------" />
</StackPanel>
</DataTemplate>
</ListBox.ItemTemplate>
</ListBox>
</Grid>
</Window>
Below is my Window.xaml.cs code:
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 DataBindingInWPF
{
/// <summary>
/// Interaction logic for
Window1.xaml
/// </summary>
public partial class Window1 : Window
{
public Window1()
{
InitializeComponent();
}
private void
Window_Loaded(object sender, RoutedEventArgs e)
{
BindData();
}
public void
BindData()
{
using (SqlConnection
con = new SqlConnection("Data Source=.; Initial Catalog=Test; Uid=sa;
pwd=pwd"))
{
SqlCommand cmd = new
SqlCommand("Select
* From Employee", con);
DataSet ds = new DataSet();
SqlDataAdapter da = new
SqlDataAdapter();
try
{
con.Open();
da.SelectCommand = cmd;
da.Fill(ds, "EMP");
lstEmployee.DataContext = ds;
}
catch (Exception
ex)
{
}
finally
{
con.Close();
}
}
}
}
}
When you run the application then Output:
Image 1.