Exercise: Create, bind and format a simple datagrid

This exercise is provided to allow potential course delegates to choose the correct Wise Owl Microsoft training course, and may not be reproduced in whole or in part in any format without the prior written consent of Wise Owl.

The answer to the exercise will be included and explained if you attend the Wise Owl course listed below!

Category ==> WPF - Visual C#  (20 exercises)
Topic ==> Datagrids  (2 exercises)
Level ==> Relatively easy
Course ==> WPF using Visual C#
Before you can do this exercise, you'll need to download and unzip this file (if you have any problems doing this, click here for help).

You need a minimum screen resolution of about 700 pixels width to see our exercises. This is because they contain diagrams and tables which would not be viewable easily on a mobile phone or small laptop. Please use a larger tablet, notebook or desktop computer, or change your screen resolution settings.

If necessary, run the SQL script in the above folder to generate the database of Top Trumps cards:

Table of Top Trumps cards

The table called tblCard whose CardTitle and Description fields we'll display.

Create a window called Geeks, and get it to show a DataGrid showing all of the cards whose PackId equals 1, using the default setting of autogenerating columns:

Basic datagrid of geeks

There is no shame - quite the opposite, in fact - in copying and pasting your code-behind to populate the data table of cards.  You can then set the ItemsSource of the datagrid to bind to this table.


Now set AutoGenerateColumns to False, and add columns to your datagrid to show the card title and description:

Datagrid of cards with text columns

The new version of the datagrid includes two columns only.


Now apply the following formatting and changes:

  1. Set the CanUserSortColumns property of the DataGrid and the SortMemberPath of each column so that sorting works (you could also set the SortDirection property of the card title column so that initially the geeks are sorted by their card title).
  2. Unset the CanUserAddRows property.
  3. Set a row background and alternating row background for the datagrid.
  4. Set suitable widths for each column.

You can see the effect of these changes on the next page.

This is how your datagrid might look after your formatting changes:

Formatted datagrid

The datagrid with the above changes applied.


Finally, attach code to the MouseDoubleClick event of your datagrid so that you see the title of the chosen card as a message box title, and the description as the message:

Steve Jobs message

What you would see if you were to double-click on Steve Jobs.

Close down this window!

This page has 0 threads Add post