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:

<Grid x:Name=”Grid1″>

<ListView Name=”ListViewEmployeeDetails” Margin=”4,20,40,100″ ItemTemplate=”{DynamicResource EmployeeTemplate}” ItemsSource=”{Binding Path=Table}”>

<ListView.Background>

<LinearGradientBrush>

<GradientStop Color=”Gray” Offset=”0″/>

</LinearGradientBrush>

</ListView.Background>

<ListView.View>

<GridView>

<GridViewColumn Header=”Employee ID” DisplayMemberBinding=”{Binding Path=EmployeeID}”/>

<GridViewColumn Header=”First Name” DisplayMemberBinding=”{Binding Path=FirstName}”/>

<GridViewColumn Header=”Last Name” DisplayMemberBinding=”{Binding Path=LastName}”/>

<GridViewColumn Header=”BirthDate” DisplayMemberBinding=”{Binding Path=BirthDate}”/>

<GridViewColumn Header=”City” DisplayMemberBinding=”{Binding Path=City}”/>

<GridViewColumn Header=”Country” DisplayMemberBinding=”{Binding Path=Country}”/>

</GridView>

</ListView.View>

</ListView>

</Grid>

Here is .cs code:

SqlConnection con = new SqlConnection();

SqlDataAdapter ad = new SqlDataAdapter();

SqlCommand cmd = new SqlCommand();

String str = “SELECT EmployeeID, FirstName, LastName, BirthDate, City, Country FROM Employees”;

cmd.CommandText = str;

ad.SelectCommand = cmd;

con.ConnectionString = “Data Source=localhost; Initial Catalog=Northwind; Integrated Security=True”;

cmd.Connection = con;

DataSet ds = new DataSet();

ad.Fill(ds);

ListViewEmployeeDetails.DataContext = ds.Tables[0].DefaultView;

con.Close(); 

Note:  Add two namespace.

using System.Data.SqlClient;
using System.Data; 

Snapshot:

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s