Mastering WPF DataGrid in a Day: Hour 1 Introduction

In this article of the series, I will cover almost everything you will need to master the WPF DataGrid control and its functionality. This article is the first article of the series, introduction to simple data binding.

The WPF DataGrid is one of the most widely used controls. The DataGrid control displays data in a row and column format. The DataGrid not only allows you to display data in a grid format but also lets you add, update, delete, filter and sort data displayed in the control. In this e-book, you will learn how to use a DataGrid control in your real-world applications.

In this series, we will cover the following topics:
  • Create a DataGrid
  • Data Binding
  • DataGrid Properties
  • DataGrid Header
  • Row Details
  • Add Remove Columns
  • Frozen Column
  • Show Selected Row Information
  • Data Filter
  • Sorting in DataGrid
  • Drag and Drop Data Binding
  • Master Details Data Display
  • Grouping
  • Data Entry with Images
  • DataGrid Style
  • CRUD in DataGrid
The preceding topics may be updated as I move to the topics.

Creating a DataGrid

Like any other control, there are two ways to create a DataGrid control; at design-time and at run-time. In most of the cases, you're likely to use a design-time approach to create a control. You may end up adjusting the control layout and position at run-time.

In the design-time approach, you use the Visual Studio IDE designer to drag and drop the DataGrid control from the Toolbox to a window. You can use drag and drop to move, resize and position the control. Alternatively, you can also type in all the code by hand in the XAML file.

Create a New WPF Application

Create a WPF application using the Visual Studio IDE and drag and drop a DataGrid control from the Toolbox to the window. Figure 1 shows the IDE Toolbox, the page and XAML code preview after a DataGrid is dropped to a window.

Figure 1

You can use the Grid handles to resize and move the DataGrid control. Go ahead and place the control whereever you like and resize it using the bottom-right and other corners. My final DataGrid looks like Figure 2.

Figure 2

When you use the Visual Studio IDE designer, the designer not only creates the control layout but also creates the XAML code. Listing 1 is the typical XAML written by the designer. 
  1. <Window x:Class="DataGridSample.MainWindow"  
  2.    xmlns=""  
  3.    xmlns:x=""  
  4.    Title="MainWindow" Height="389.801" Width="650" Loaded="Window_Loaded">  
  5.    <Grid>  
  6.       <DataGrid HorizontalAlignment="Left" Margin="10,10,0,0" VerticalAlignment="Top"  
  7.          Height="219" Width="465"/>  
  8.    </Grid>  
  9. </Window>  
Listing 1

The DataGrid element in XAML represents a DataGrid control. The Width and Height properties represent the width and the height of a DataGrid. The Margin property sets the placement margins of the DataGrid on a window. The Name property represents the name of the control, which is a unique identifier of a control. As you can see from the listing, the designer does not add the Name property. So we will add it manually. Now the final DataGrid XAML is listed in Listing 2. 
  1. <DataGrid HorizontalAlignment="Left" Margin="10,10,0,0" VerticalAlignment="Top"  
  2. Height="219" Width="465" Name="McDataGrid"/>  
Listing 2

Data Binding

Once a DataGrid control is created, now the next step is to display some data in it. As we discussed earlier, a DataGrid control displays data in a grid (tabular data). A grid is a collection of rows and columns so our data must also be in the same format.

Data Collection

Before we can display any data in a DataGrid, we must have some data. The data that is a collection of objects.

Let's create a class that has some public properties. The code snippet in Listing 3 defines the Author class that has five public properties. The properties are ID, Name, DOB, BookTitle and IsMVP or int, string, DateTime, string and bool types.
  1. public class Author  
  2. {  
  3.    public int ID { get; set; }  
  4.    public string Name { get; set; }  
  5.    public DateTime DOB { get; set; }  
  6.    public string BookTitle { get; set; }  
  7.    public bool IsMVP { get; set; }  
  8. }  
Listing 3
Now, we have an object. All we need to do is, create a collection of it. Once we have a collection of objects, we will be able to display its data in a DataGrid.
The code snippet in Listing 4 creates a List of Author objects using the LoadCollectionData method. 
  1. public class AuthorCollection : CollectionBase  
  2. {  
  3.    /// <summary>  
  4.    /// List of Authors  
  5.    /// </summary>  
  6.    /// <returns></returns>  
  7.    public List<Author> LoadAuthors()  
  8.    {  
  9.       List<Author> authors = new List<Author>();  
  10.       authors.Add(new Author()  
  11.       {  
  12.          ID = 101,  
  13.          Name = "Mahesh Chand",  
  14.          BookTitle = "Graphics Programming with GDI+",  
  15.          DOB = new DateTime(1975, 2, 23),  
  16.          IsMVP = false  
  17.       });  
  18.       authors.Add(new Author()  
  19.       {  
  20.          ID = 201,  
  21.          Name = "Mike Gold",  
  22.          BookTitle = "Programming C#",  
  23.          DOB = new DateTime(1982, 4, 12),  
  24.          IsMVP = true  
  25.       });  
  26.       authors.Add(new Author()  
  27.       {  
  28.          ID = 244,  
  29.          Name = "Dhananjay Kumar",  
  30.          BookTitle = "ADO.NET Development",  
  31.          DOB = new DateTime(1985, 9, 11),  
  32.          IsMVP = true  
  33.       });  
  34.       return authors;  
  35.    }  
  36. }  
Listing 4

The ItemSource property of the DataGrid is the key to the data binding. The user can bind any data source that implements IEnuemerable. Each row in the DataGrid is bound to an object in the data source and each column in the DataGrid is bound to a property of the data source objects. To display a collection of data in a DataGrid, we simply need to bind its ItemsSource property to the Author collection that we created in the AuthorCollection class in Listing 4. Double-click or use the Properties windows and create a Window Loaded event handler. See Listing 5. On the Window's Loaded event handler, we create an AuthorCollection object and call its LoadAuthors() method to bind to the DataGrid by setting DataGrid's ItemsSource property. 
  1. private void Window_Loaded(object sender, RoutedEventArgs e)  
  2. {  
  3. AuthorCollection authors = new AuthorCollection();  
  4. McDataGrid.ItemsSource = authors. LoadAuthors();  
  5. }  
Listing 5
Build and Run

Now let's build and run our application (Hit F5). The output looks as in Figure 3. As you can see from Figure 3, the object properties names are automatically generated as DataGrid columns with the title being the property name.

Figure 3

In this first article of the Mastering WPF DataGrid series, we saw how to create a DataGrid using Visual Studio and display some data in it. In the next article of this series, I will cover some of the common properties of the WPF DataGrid.

Next Article: Mastering WPF DataGrid in a Day: Hour 2 Layout