Friday, August 20, 2010

WPF ListView and LINQ

After dealing with traditional WinForms DataGridViews, when you are trying to display information, I find that ListView in WPF is much more easy to code.

We start with the declaration of our ListView in XAML:

                <ListView Name="lvPersons">
                                DisplayMemberBinding="{Binding First_Name}"
                                Header="First Name" />
                                DisplayMemberBinding="{Binding Last_Name}"
                                Header="Last Name/>
                                DisplayMemberBinding="{Binding SSN}"
                                Header="Social Security Number" />

Now, based on the example, the data set I will be using will consist of three columns: "First Name", "Last Name" and "SSN". If you notice, when your column names have spaces, LINQ (which I will be using to bind my dataset to the listview) replaces them with underscores ( _ ).

So, I have a LINQ dataset, which either has a table with this format or a stored procedure that returns results in this format. Now, the dataset could have more than these columns. It can even have less! (In this case, the column will not be populated).

To populate the ListView, simply add this code where appropriate:

                // Populate the data layer class
                MyDataLayer _db = new MyDataLayer();
                // Populate the ListView
                lvPersons.ItemsSource = _db.getFullTimeEmployees();

That's it!

In a later post, I'll go into custom formatting values.

No comments:

Post a Comment