Skip to main content

How to: Implement Custom Grouping

  • 2 minutes to read

This example shows how to group rows using custom rules. When grouping by the 'Unit Price' column, the rows in this column that have values between 0 and 10 should be combined into a single group. Rows whose values fall between 10 and 20 should be combined into another group, etc.

<Page
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    xmlns:local="using:HowToCustomGrouping"
    xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
    xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
    xmlns:Grid="using:DevExpress.UI.Xaml.Grid"
    x:Class="HowToCustomGrouping.MainPage"
    mc:Ignorable="d">
    <Grid>
        <Grid:GridControl Name="grid" CustomColumnGroup="GridControl_CustomColumnGroup" CustomGroupDisplayText="GridControl_CustomGroupDisplayText" Background="Black" Foreground="White" >
            <Grid:GridControl.Columns>
                <Grid:GridTextColumn FieldName="ProductName" />
                <Grid:GridTextColumn FieldName="Supplier" />
                <Grid:GridTextColumn FieldName="UnitPrice" SortMode="Custom"/>
                <Grid:GridTextColumn FieldName="Quantity" />
            </Grid:GridControl.Columns>
        </Grid:GridControl>
    </Grid>
</Page>
using System;
using System.Collections.Generic;
using Windows.UI.Xaml.Controls;

namespace HowToCustomGrouping
{
    public sealed partial class MainPage : Page
    {
        public MainPage()
        {
            this.InitializeComponent();
            grid.ItemsSource = new ProductList();
            grid.Columns["UnitPrice"].GroupIndex = 0;
        }

        private void GridControl_CustomColumnGroup(object sender, DevExpress.UI.Xaml.Grid.CustomColumnSortEventArgs e) {
            if (e.Column.FieldName == "UnitPrice") {
                double x = Math.Floor(Convert.ToDouble(e.Value1) / 10);
                double y = Math.Floor(Convert.ToDouble(e.Value2) / 10);
                int res = Comparer<double>.Default.Compare(x,y);
                if (x > 9 && y > 9) res = 0;
                e.Result = res;
                e.Handled = true;
            }
        }

        private void GridControl_CustomGroupDisplayText(object sender, DevExpress.UI.Xaml.Grid.CustomGroupDisplayTextEventArgs e) {
            if (e.Column.FieldName != "UnitPrice") return;
            string interval = IntervalByValue(e.Value);
            e.DisplayText = interval;

        }
        private string IntervalByValue(object val) {
            double d = Math.Floor(Convert.ToDouble(val) / 10);
            string ret = string.Format("{0:c} - {1:c} ", d * 10, (d + 1) * 10);
            if (d > 9) ret = string.Format(">= {0:c} ", 100);
            return ret;
        }

    }
}