WPF: Populating a datagrid using a collection

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.

MainWindow.xaml
<Window x:Class="DataGridSpace.MainWindow"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    Title="Window1" Height="350" Width="300">
    <StackPanel>
        <DataGrid AutoGenerateColumns="True" Name="dg"  />
    </StackPanel>
</Window>

MainWindow.xaml.cs
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()
        {
            InitializeComponent();

            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;
        }
    }
}
datagrid1

 

 

 

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