Jul 15, 2015

The DataGrid control

The DataGrid control looks a lot like the ListView, when using a GridView, but it offers a lot of additional functionality. For instance, the DataGrid can automatically generate columns, depending on the data you feed it with. The DataGrid is also editable by default, allowing the end-user to change the values of the underlying data source.
The most common usage for the DataGrid is in combination with a database, but like most WPF controls, it works just as well with an in-memory source, like a list of objects. Since it's a lot easier to demonstrate, we'll mostly be using the latter approach in this tutorial.

A simple DataGrid

You can start using the DataGrid without setting any properties, because it supports so much out of the box. In this first example, we'll do just that, and then assign a list of our own User objects as the items source:

<Window x:Class="WpfTutorialSamples.DataGrid_control.SimpleDataGridSample"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        Title="SimpleDataGridSample" Height="180" Width="300">
    <Grid Margin="10">
                <DataGrid Name="dgSimple"></DataGrid>
        </Grid>
</Window>
 
 
using System;
using System.Collections.Generic;
using System.Windows;
namespace WpfTutorialSamples.DataGrid_control
{
        public partial class SimpleDataGridSample : Window
        {
                public SimpleDataGridSample()
                {
                        InitializeComponent();

                        List<User> users = new List<User>();
                        users.Add(new User() { Id = 1, Name = "John Doe", Birthday = new DateTime(1971, 7, 23) });
                        users.Add(new User() { Id = 2, Name = "Jane Doe", Birthday = new DateTime(1974, 1, 17) });
                        users.Add(new User() { Id = 3, Name = "Sammy Doe", Birthday = new DateTime(1991, 9, 2) });

                        dgSimple.ItemsSource = users;
                }
        }

        public class User
        {
                public int Id { get; set; }

                public string Name { get; set; }

                public DateTime Birthday { get; set; }
        }
}

 


That's really all you need to start using the DataGrid. The source could just as easily have been a database table/view or even an XML file - the DataGrid is not picky about where it gets its data from.
If you click inside one of the cells, you can see that you're allowed to edit each of the properties by default. As a nice little bonus, you can try clicking one of the column headers - you will see that the DataGrid supports sorting right out of the box!
The last and empty row will let you add to the data source, simply by filling out the cells.

No comments:

Post a Comment