Data Binding in WPF ListView

In this article, I am going to explain how to extract data from database and how to show data on a page using WPF ListView control.

I am using Northwind database, you can use whatever you want, and only you have to change is the connection string, your SQL string, and the binding properties in XAML code.
 
Here is the. xaml code: 

  1. <Grid x:Name="Grid1">  
  2.   <ListView Name="ListViewEmployeeDetails" Margin="4,20,40,100" ItemTemplate="{DynamicResource EmployeeTemplate}" ItemsSource="{Binding Path=Table}">  
  3.     <ListView.Background>  
  4.       <LinearGradientBrush>  
  5.         <GradientStop Color="Gray" Offset="0"/>             
  6.       </LinearGradientBrush>  
  7.     </ListView.Background>  
  8.     <ListView.View>           
  9.       <GridView>  
  10.         <GridViewColumn Header="Employee ID" DisplayMemberBinding="{Binding Path=EmployeeID}"/>  
  11.         <GridViewColumn Header="First Name" DisplayMemberBinding="{Binding Path=FirstName}"/>  
  12.         <GridViewColumn Header="Last Name" DisplayMemberBinding="{Binding Path=LastName}"/>  
  13.         <GridViewColumn Header="BirthDate" DisplayMemberBinding="{Binding Path=BirthDate}"/>  
  14.         <GridViewColumn Header="City" DisplayMemberBinding="{Binding Path=City}"/>  
  15.         <GridViewColumn Header="Country" DisplayMemberBinding="{Binding Path=Country}"/>  
  16.       </GridView>  
  17.     </ListView.View>  
  18.   </ListView>  
  19. </Grid>  

Here is .cs code:

  1. SqlConnection con = new SqlConnection();  
  2. SqlDataAdapter ad = new SqlDataAdapter();  
  3. SqlCommand cmd = new SqlCommand();  
  4. String str = "SELECT EmployeeID, FirstName, LastName, BirthDate, City, Country FROM Employees";  
  5. cmd.CommandText = str;  
  6. ad.SelectCommand = cmd;  
  7. con.ConnectionString = "Data Source=localhost; Initial Catalog=Northwind; Integrated Security=True";  
  8. cmd.Connection = con;  
  9. DataSet ds = new DataSet();  
  10. ad.Fill(ds);  
  11. ListViewEmployeeDetails.DataContext = ds.Tables[0].DefaultView;  
  12. con.Close();  
Note: Add two namespace.
  1. using System.Data.SqlClient;  
  2. using System.Data;  
Snapshot

Data Binding in WPF ListView

I hope you will like this article. If yes drop me a line or write a comment below in the comments section.