6
9

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 1 year has passed since last update.

WPF DataGridでExcelのようにセルを範囲選択して集計してくだされ

Last updated at Posted at 2022-02-24

業務アプリケーションを開発した時にExcelを使いこなすユーザーがいらっしゃいました。
使い続けていくうちにDataGridがワークシートに見えたのか、このようなリクエストが来ました。
「えぇ~~~っ!」と思ったのですが、結果的に懇切丁寧にDataGridにフィルタ機能や集計機能を実装するよりも工数削減になりました。
最初っから思考的に拒絶してはいかんですね。
image.png

MainWindow.xaml
<Window x:Class="GridSample.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:GridSample"
        mc:Ignorable="d"
        Title="MainWindow" 
        Height="270" Width="500">
    <StackPanel>
        <DataGrid x:Name="dataGrid"
                  SelectedCellsChanged="DataGrid_SelectedCellsChanged" SelectionUnit="Cell"/>

        <!-- リアルタイム集計値の表示エリア -->
        <Border Padding="5" Background="LightGray">
            <StackPanel Orientation="Horizontal">
                <TextBlock Width="150" x:Name="lblAverage" Text="平均" Margin="12,0,0,0"/>
                <TextBlock Width="150" x:Name="lblCount" Text="選択セルの個数" Margin="12,0,0,0"/>
                <TextBlock Width="150" x:Name="lblSum" Text="合計"  />
            </StackPanel>
        </Border>
    </StackPanel>
</Window>
MainWindow.xaml.cs
using System;
using System.Collections.ObjectModel;
using System.Windows;
using System.Windows.Controls;

namespace GridSample
{
    /// <summary>
    /// MainWindow.xaml の相互作用ロジック
    /// </summary>
    public partial class MainWindow : Window
    {
        public MainWindow()
        {
            InitializeComponent();


            ObservableCollection<SampleRecord> records = new ObservableCollection<SampleRecord>();
            records.Add(new SampleRecord()
            {
                Name = "A",
                Number1 = 1000,
                Number2 = 2000,
            });
            records.Add(new SampleRecord()
            {
                Name = "B",
                Number1 = 7000,
                Number2 = 6000,
            });

            records.Add(new SampleRecord()
            {
                Name = "C",
                Number1 = 4000,
                Number2 = 5000,
            });
            this.dataGrid.ItemsSource = records;
        }


        private void DataGrid_SelectedCellsChanged(object sender, SelectedCellsChangedEventArgs e)
        {
            int cellCount = 0;
            int cellCountOfTypeNumber = 0;
            decimal average = 0;
            decimal sum = 0;

            foreach (var cell in dataGrid.SelectedCells)
            {
                if (cell != null)
                {
                    // 値があるセルであれば、カウントを増やす
                    cellCount += 1;
                    decimal addSum = 0;
                    // 数値項目か判定
                    string value = ((TextBlock)cell.Column.GetCellContent(cell.Item)).Text;
                    if (Decimal.TryParse(value, out addSum))
                    {
                        // 平均値を算出するため、数値型のセルのカウントを行う
                        cellCountOfTypeNumber += 1;
                        // 合計値を加算
                        sum += addSum;
                    }
                }
            }
            //  選択されたセルの情報を、各項目に反映する
            if (cellCountOfTypeNumber >= 1)
            {
                average = sum / cellCountOfTypeNumber;
            }
            lblAverage.Text = string.Format("平均 : {0:#,0}", average);
            lblCount.Text = string.Format("データの個数 : {0}", cellCount);
            lblSum.Text = string.Format("合計 : {0:#,0}", sum);
        }
    }
}
6
9
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
6
9

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?