WPF: Populating a datagrid using a collection

This entry is part 37 of 54 in the series Learn WPF

To populate a data into a datagrid, we can first add the data into a collection.

Here we first declare an instance of ObservableCollection and add some items into a Customer class.

We have given a name dg to the DataGrid and by using ItemSource property of the grid, we can populate the data into the grid by assigning the collection to the data grid ItemSource.

<Window x:Class="DataGridSpace.MainWindow"
    Title="Window1" Height="350" Width="300">
        <DataGrid AutoGenerateColumns="True" Name="dg"  />

using System.Collections.ObjectModel;
using System.Windows;

namespace DataGridSpace
    public class Customer
        public int ID { get; set; }
        public string Name { get; set; }
        public string SecNumber { get; set; }

    public partial class MainWindow : Window
        ObservableCollection<Customer> col;

        public MainWindow()

            col = new ObservableCollection<Customer>();

            col.Add(new Customer() { ID = 1, Name = "John", SecNumber = "A498" });
            col.Add(new Customer() { ID = 2, Name = "Michelle", SecNumber = "B812" });
            col.Add(new Customer() { ID = 3, Name = "Emily", SecNumber = "B871" });
            col.Add(new Customer() { ID = 4, Name = "David", SecNumber = "D455" });

            dg.ItemsSource = col;




Series Navigation<< WPF: Using an instance name for the listview
WPF: Adding and deleting items in DataGrid >>