WPF: Datagrid Grouping

This article will show you how to create WPF Datagrid Datagrid Grouping. I assume you already know how to display data in a Datagrid. We need to use a ListCollectionView as the Datagrid itemsource because that class has a property named GroupDescriptions. GroupDescriptions is used for grouping.

For the sample I used a WPF project with C# Language as below:


There is already MainWindow.xaml to be a startup form and we'll use it for displaying data on Datagrid with group. 

The below code is for MainWindow.xaml with the standard grid before it's grouped.

<Window x:Class="WpfApplication1.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:WpfApplication1"
    mc:Ignorable="d"
    Title="MainWindow" Height="350" Width="675">
  <Grid>
    <DataGrid x:Name="myDataGrid" CanUserAddRows="False" 
              AutoGenerateColumns="False">
        <DataGrid.Columns>
          <DataGridTextColumn x:Name="ColumnMonth" Header="Month" 
                   Width="100" Binding="{Binding Month}"/>
          <DataGridTextColumn x:Name="ColumnCode" Header="Barcode" 
                   Width="100" Binding="{Binding Barcode}"/>
          <DataGridTextColumn x:Name="ColumnName" Header="Item Name" 
                   Width="150" Binding="{Binding ItemName}"/>
          <DataGridTextColumn x:Name="ColumnPrice" Header="Price" 
                   Width="100" Binding="{Binding Price,StringFormat=N0}" />
          <DataGridTextColumn x:Name="ColumnQty" Header="Qty" 
                   Width="100" Binding="{Binding Qty,StringFormat=N0}" />
          <DataGridTextColumn x:Name="Columnsubotal" Header="Sub Total" 
                   Width="100" Binding="{Binding SubTotal,StringFormat=N0}" />
        </DataGrid.Columns>
     </DataGrid>
  </Grid>
</Window>


Then for the MainWindow.xaml design we'll add DataGrid.GroupStyle for creating group design. Below is the code after adding a grouping style. I give a yellow highlight to the code for grouping style. I also delete the DataGridTextColumn, it's deleted because becoming a group value. 

<Window x:Class="WpfApplication1.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:WpfApplication1"
    mc:Ignorable="d"
    Title="MainWindow" Height="350" Width="675">
  <Grid>
    <DataGrid x:Name="myDataGrid" CanUserAddRows="False" 
              AutoGenerateColumns="False">
          <DataGrid.GroupStyle>
            <GroupStyle>
              <GroupStyle.ContainerStyle>
                  <Style TargetType="{x:Type GroupItem}">
                      <Setter Property="Template">
                          <Setter.Value>
                            <ControlTemplate TargetType="{x:Type GroupItem}">
                                <StackPanel>
                                    <StackPanel Orientation="Horizontal">
                                      <TextBlock Text="{Binding Name}" />
                                      <TextBlock Text="{Binding ItemCount, 
                                          StringFormat=Count: {0}}" 
                                          Margin="30,0,0,0" />
                                    </StackPanel>
                                    <ItemsPresenter />
                                </StackPanel>
                            </ControlTemplate>
                          </Setter.Value>
                      </Setter>
                  </Style>
              </GroupStyle.ContainerStyle>
            </GroupStyle>
          </DataGrid.GroupStyle>
        
          <DataGrid.Columns>
          <DataGridTextColumn x:Name="ColumnCode" Header="Barcode" 
                   Width="100" Binding="{Binding Barcode}"/>
          <DataGridTextColumn x:Name="ColumnName" Header="Item Name" 
                   Width="150" Binding="{Binding ItemName}"/>
          <DataGridTextColumn x:Name="ColumnPrice" Header="Price" 
                   Width="100" Binding="{Binding Price,StringFormat=N0}" />
          <DataGridTextColumn x:Name="ColumnQty" Header="Qty" 
                   Width="100" Binding="{Binding Qty,StringFormat=N0}" />
          <DataGridTextColumn x:Name="Columnsubotal" Header="Sub Total" 
                   Width="100" Binding="{Binding SubTotal,StringFormat=N0}" />
        </DataGrid.Columns>
     </DataGrid>
  </Grid>
</Window>


Done with the UI, let's see the behind code in MainWindow.xaml.cs. 

As I said before we'll add a class of object name sales. If you're on a bigger project it'll be better to write this class in a separate file. I created it in 1 file for simplification.

 public class Sales
  {
    public string Month { get; set; }
    public string Barcode { get; set; }
    public string ItemName { get; set; }
    public double Price { get; set; }
    public int Qty { get; set; }
    public double SubTotal { get; set; }
  }

On the top of  MainWindow.xaml.cs code we need to use some classes as below.

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

Then we declare Sales an ObservableCollection of sales and add it manually by sales.Adds to fill each row values. 

The yellow highlighted code is to covert the ObservableCollection into ListCollectionView and add its GroupDescriptions with the "Month" field.

Bagian code yang tersorot warna kuning adalah code untuk menampilkan grouping di datagarid.

public partial class MainWindow : Window
{
    ObservableCollection<Sales> sales = new ObservableCollection<Sales>();
    public MainWindow()
    {
        InitializeComponent();
        sales.Add(new Sales { Month = "January", Barcode = "A0123001",
                              ItemName = "Ultra Milk", Price = 3500,
                              Qty = 2, SubTotal = 7000 });
        sales.Add(new Sales { Month = "January", Barcode = "A0123002",
                              ItemName = "Cimory Yogurt", Price = 9500,
                              Qty = 5, SubTotal = 47500 });
        sales.Add(new Sales { Month = "January", Barcode = "A0123003",
                              ItemName = "Boba Milkshake", Price = 12000,
                              Qty = 3, SubTotal = 36000 });
        sales.Add(new Sales { Month = "February", Barcode = "A0123001",
                              ItemName = "Ultra Milk", Price = 3500,
                              Qty = 5, SubTotal = 17500 });
        sales.Add(new Sales { Month = "February", Barcode = "A0123002",
                              ItemName = "Cimory Yogurt", Price = 9500,
                              Qty = 10, SubTotal = 95000 });
        sales.Add(new Sales { Month = "March", Barcode = "A0123001",
                              ItemName = "Ultra Milk", Price = 3500,
                              Qty = 15, SubTotal = 52500 });
        sales.Add(new Sales { Month = "March", Barcode = "A0123002",
                              ItemName = "Cimory Yogurt", Price = 190000,
                              Qty = 20, SubTotal = 47500 });
        sales.Add(new Sales { Month = "March", Barcode = "A0123003",
                              ItemName = "Boba Milkshake", Price = 12000,
                              Qty = 2, SubTotal = 24000 });
        sales.Add(new Sales { Month = "March", Barcode = "A0123003",
                              ItemName = "Yakult", Price = 1000,
                              Qty = 12, SubTotal = 12000 });



        ListCollectionView collectionView = new ListCollectionView(sales);
         collectionView.GroupDescriptions.Add(new
                                      PropertyGroupDescription("Month"));
        myDataGrid.ItemsSource = collectionView;

    }
}

Let's try to run and debug.


You can also download the source code by below link:

Download

Post a Comment

0 Comments