Subscribe to Subscribers

Resources » Code Snippets » Databinding

How to Bind Data to a ListView Control in WPF ?


Posted Date:     Category: Databinding    
Author: Member Level: Gold    Points: 15


DataGridView Control is not available in WPF application. Most of the time the requirement is to show data in tabulated form. In this article, I will explain how to use ListView Control in WPF to tabulate data by binding a DataTable. This articles also explain WPF and Database onnectivity using ADO.Net classes.



Introduction



When I started working on Windows Presentation Foundation (WPF) with ADO.Net, I realized the very much important control used in Windows Application to present data in tabulated form the DataGridView control is not present in the control list. In most of the management related applications there is always need to display data is tables. I was searching for a solution in WPF and finally I learned how we can use ListView control to tabulate data.

Getting Started


We are going to learn WPF Data Binding using ADO.Net with an example.

Step 1
Create a table Employee in the SQL Server database and add few records to it as follows.


CREATE TABLE EMPLOYEE
(
EID INT PRIMARY KEY IDENTITY(1,1),
ENAME VARCHAR(50) NOT NULL,
SALARY DECIMAL(9,2)
)

INSERT INTO EMPLOYEE VALUES ('Asheej',67000)
INSERT INTO EMPLOYEE VALUES ('Tony',126000)
INSERT INTO EMPLOYEE VALUES ('Paritosh',83000)
INSERT INTO EMPLOYEE VALUES ('Anil',89000)


Step 2
Take a new WPF Application. In the Visual Studio
File -> New -> Project -> Select WPF Application Under Visaul C# Windows Category -> Give it Name as DataBindingDemo - OK

Image 1



Step 3
You can see the Window1.xaml file on your screen. Next we have to add a ListView control and a button inside the <Grid> and </Grid> tags. On the button's click we will load the data from the database table into the ListView.

Place the following code between the <Grid> and </Grid> tags of the Window1.xaml file for adding ListView and a Button control.


<ListView Margin="10,10,11,49" Name="listView1"
ItemTemplate="{DynamicResource Employeetemplate}"
ItemsSource="{Binding Path=Table}" SelectionMode="Single">
<ListView.Background>
<LinearGradientBrush>
<GradientStop Color="AliceBlue" Offset="0"/>
</LinearGradientBrush>
</ListView.Background>
<ListView.View>
<GridView>
<GridViewColumn Header="Employee ID" DisplayMemberBinding="{Binding Path=EID}"/>
<GridViewColumn Header="Employee Name" DisplayMemberBinding="{Binding Path=ENAME}"/>
<GridViewColumn Header="Salary" DisplayMemberBinding="{Binding Path=SALARY}"/>
</GridView>
</ListView.View>
</ListView>
<Button Margin="111,0,99,10" Name="btnFillData" Height="23"
VerticalAlignment="Bottom">Fill Data</Button>


And now the Window1.xaml file will have the following user interface.

Image 2



What is important in the above code?


The above code simply adds a ListView control (listView1) and a button (btnFillData). The following lines are important in the code.

<ListView.View>
<GridView>
<GridViewColumn Header="Employee ID" DisplayMemberBinding="{Binding Path=EID}"/>
<GridViewColumn Header="Employee Name" DisplayMemberBinding="{Binding Path=ENAME}"/>
<GridViewColumn Header="Salary" DisplayMemberBinding="{Binding Path=SALARY}"/>
</GridView>
</ListView.View>


The code changes the View style of listView1 to Grid and adds three columns with headings Employee ID, Employee Name and Salary which are binded to the Employee table's columns EID, ENAME and SALARY respectively.

Step 4
Now remains the ADO.Net code for binding an SQL Server database. In the Window1.xaml.cs file we need to use the following namespaces.


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


Create objects of necessary classes and initialize them as follows.

SqlConnection con;
SqlDataAdapter da;
DataSet ds;

public Window1()
{
InitializeComponent();
con = new SqlConnection("Data Source=.;Initial Catalog=DNS;
Integrated Security=True");
ds = new DataSet();
}


Step 5
Go back to Window1.xaml file and double click on the button. Place the following code on button's click event.

private void btnFillData_Click(object sender, RoutedEventArgs e)
{
da = new SqlDataAdapter("SELECT * FROM EMPLOYEE", con);
da.Fill(ds, "emp");
listView1.DataContext = ds.Tables["emp"].DefaultView;
}


Now we are done with Everything. Execute the application and check the output. You will find a good looking listView1 control. Click on the Fill Data Button and the table is displayed in the ListView.

image 3



Hence in WPF we can use the ListView control to fill the gap created by the non availability of DataGridView.

You can also find the demo application in the attachment. Download it for your reference.

I hope that this article will add value to your knowledge and you like the simple and clean explanation.

(Don't forget to rate the content and leave your responses.)

Thanks 'n Regards,
Sibtain Masih

Attachments
  • DataBindingDemo (43117-232212-DNS-DataBindingDemo.rar)





  • Did you like this resource? Share it with your friends and show your love!


    Responses to "How to Bind Data to a ListView Control in WPF ?"
    Author: AnnieCalvert    03 Aug 2012Member Level: Bronze   Points : 1
    Its a 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.
    http://www.dapfor.com/en/net-suite/net-grid/tutorial/data-binding



    Guest Author: manasa     25 Sep 2012
    can u please explain how to apply filter concept based on the value entered in the textbox to this example.


    Feedbacks      

    Post Comment:




  • Do not include your name, "with regards" etc in the comment. Write detailed comment, relevant to the topic.
  • No HTML formatting and links to other web sites are allowed.
  • This is a strictly moderated site. Absolutely no spam allowed.
  • Name:   Sign In to fill automatically.
    Email: (Will not be published, but required to validate comment)



    Type the numbers and letters shown on the left.


    Next Resource: Retrieving random records from Database
    Previous Resource: Common function to Retrieve a DataTable using a StoredProcedure
    Return to Resources
    Post New Resource
    Category: Databinding


    Post resources and earn money!
     
    More Resources
    Popular Tags   Tag posting guidelines   Search Tags  
    WPF  .  ListView  .  ADO.Net  .  

    Active Members
    TodayLast 7 Daysmore...

    Awards & Gifts
    Talk to Webmaster Tony John
    Copyright © SpiderWorks Technologies Pvt Ltd., Kochi, India
    2005 - 2013 All Rights Reserved.
    .NET and other trademarks mentioned in this site belong to Microsoft and other respective trademark owners.
    Articles, tutorials and all other content offered here is for educational purpose only.
    We are not associated with Microsoft or its partners.