Reader Level:
ARTICLE

Data Binding in WPF ListView

Posted by Raj Kumar Articles | WPF October 05, 2007
This article shows how to extract data from a database and show in a WPF ListView control.
  • 0
  • 0
  • 186665
 

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:

 

bindingwpf.JPG

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

Article Extensions
Contents added by anver sadat on Sep 04, 2010
Hi,
   Nice Article on dynamic Binding in wpf Technology.I got clear difference  between static & dynamic binding Concept. U explained it in simple and smooth way. Be continue to sharing your ideas. More articles are required in wpf Tech. I am newbie in this. So please Guide me.
thnx and regards
 anver sadat
Contents added by a b on Dec 01, 2009
Thank's for the code, it helped me a lot !
COMMENT USING

Trending up