WPF DataGrid Control Example


This entry is part 2 of 6 in the series WPF DataGrid Control

Let’s use the example in the book WPF Illustrated to create a data grid. Create a new WPF project and give it a name and locate it in your favourite folder. Below is the code I have added to the main window and below that is what it looks like when we run it. The name of the data grid is dg. Also note that the AutoGenerateColumns is False. The default is True. You can see the namespace is DataGridWPFIllustrated, and so you know that I named my project DataGridWPFIllustrated.

Below is the XAML code.

<Window x:Class="DataGridWPFIllustrated.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
        xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
        xmlns:local="clr-namespace:DataGridWPFIllustrated"
        mc:Ignorable="d"
        Title="Data Grid from WFP Illustrated" Height="450" Width="800">
    <StackPanel>
        <DataGrid Name="dg" AutoGenerateColumns="False" Margin="10">
            <DataGrid.Columns>
                <DataGridTextColumn Binding="{Binding FirstName}"
                   Header="First Name"/>
                <DataGridTextColumn Binding="{Binding LastName}"
                   Header="Last Name"/>
                <DataGridCheckBoxColumn Binding="{Binding HasRoadster}"
                   Header="Has Roadster"
                   Width="SizeToHeader"/> 
                <DataGridTextColumn Binding="{Binding Age}"
                   Header="Age"
                   Width="*"/> 
            </DataGrid.Columns>
        </DataGrid>
    </StackPanel>
</Window>

When we run the WPF program we get this.

Data

Now we need to add some data to the grid. How do we do that? Below is the whole listing for the code behind. That is in the file MainWindow.xaml.cs.

using System.Collections.Generic;
using System.Windows;
namespace DataGridWPFIllustrated
{
    /// <summary>
    /// Interaction logic for MainWindow.xaml
    /// </summary>
    public partial class MainWindow : Window
    {
        List<Person> _people = new List<Person>();
        public MainWindow()
        {
            InitializeComponent();
            _people.Add(new Person("Sherlock", "Holmes", 54, false));
            _people.Add(new Person("Jane", "Marple", 60, false));
            _people.Add(new Person("Nancy", "Drew", 16, true));
            _people.Add(new Person("Charlie", "Chan", 50, false));
            dg.ItemsSource = _people;
        }
    }
    class Person
    {
        public string FirstName { get; set; }
        public string LastName { get; set; }
        public int Age { get; set; }
        public bool HasRoadster { get; set; }
        public Person(string fName, string lName, int age, bool hasRoadster)
        {
            FirstName = fName;
            LastName = lName;
            Age = age;
            HasRoadster = hasRoadster;
        }
    }
}

Refactoring

Time for some code clean-up. I want to un-clutter the MainWindow code behind. I have done that and now we have the following code listed below. To do this, the first thing I did was to make the Person class a class of its own. Select the Project in Solution Explorer, Add, Class and call it Person. It is the same code. Below is our new code behind.

using System.Collections.Generic;
using System.Windows;
namespace DataGridWPFIllustrated
{
    public partial class MainWindow : Window
    {
        List<Person> _people = new List<Person>();
        public MainWindow()
        {
            InitializeComponent();

            _people.Add(new Person("Sherlock", "Holmes", 54, false));
            var pd = new PeopleData();
            pd.GetMorePeople(_people);
            dg.ItemsSource = _people;
        }
    }
}

using System.Collections.Generic;
namespace DataGridWPFIllustrated
{
    class PeopleData
    {
        public void GetMorePeople(List<Person> p)
        {
            p.Add(new Person("Jane", "Marple", 60, false));
            p.Add(new Person("Nancy", "Drew", 16, true));
            p.Add(new Person("Charlie", "Chan", 50, false));
            p.Add((new Person("Another", "Person", 54, false)));
        }
    }
}

Series Navigation<< WPF DataGrid Control IntroductionWPF DataGrid Control Revisited >>