いろいろ備忘録日記

主に .NET とか Go とか Flutter とか Python絡みのメモを公開しています。

DataGridView入門記-19 (セルの書式設定が行われる際のイベント)(CellFormatting)

CellFormattingイベントは、DGVがセルの書式設定を行う際に発生します。
通常は、このイベント内で仕様にしたがって、セルの書式を設定したりします。

関連するイベントとしては、値の変換時に発生するイベントであるCellParsingイベントなどがあります。


今回のサンプルでは、適当なサンプルが思い浮かばなかったのでCellFormattingイベント内で
値の変換をおこなっちゃってます。ご勘弁を。m(_ _)m
まあ、どんなもんかを確認するにはいいかもしれないです。w


以下、サンプルです。

// vim:set ts=4 sw=4 et ws is nowrap ft=cs:
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;

namespace Gsf.Samples.DGV {

    public partial class MainForm : Form {
        public MainForm() {
            InitializeComponent();
        }

        private void ConstructDataGridView() {

            DataGridViewTextBoxColumn col = new DataGridViewTextBoxColumn();

            col.HeaderText       = "ID";
            col.DataPropertyName = "Id";
            col.DisplayIndex     = 0;

            grid.Columns.Add(col);

            col = new DataGridViewTextBoxColumn();

            col.HeaderText       = "名前";
            col.DataPropertyName = "Name";
            col.DisplayIndex     = 1;

            grid.Columns.Add(col);

            grid.DataSource = GetDataSource();

            //
            // セルのフォーマット時のイベントを設定します。
            //
            grid.CellFormatting += new DataGridViewCellFormattingEventHandler(grid_CellFormatting);
        }

        /// <summary>
        /// DGVがセルの書式設定を行う際にコールバックされます。
        /// </summary>
        /// <remarks>
        /// 以下の処理を行います。
        /// ・IDカラムの値が数値として妥当な値であるかをチェック。数値に変換できない場合は、値を###とします。
        /// 
        /// [注意点]
        /// CellFormattingイベント内で処理を行う際には、ヘルプにも記載がありますが以下の点に注意する必要があります。
        /// 
        /// ■DataGridViewのセルの値を直接編集するのではなく、DataGridViewCellFormattingEventArgs.Valueの値を編集する。
        ///  (グリッドのセル値を直接編集すると、最悪の場合スタックオーバーフローします。)
        /// </remarks>
        /// <param name="sender">イベント送信元オブジェクト</param>
        /// <param name="e">イベント引数</param>
        void grid_CellFormatting(object sender, DataGridViewCellFormattingEventArgs e) {
            
            DataGridView g = sender as DataGridView;

            if(g != null && e.ColumnIndex == 0){
                string cellValue = e.Value.ToString();

                int parsedValue;
                if(!int.TryParse(cellValue, out parsedValue)){
                    //
                    // 解析に失敗した場合、セルの値を###とする。
                    //
                    e.Value = "###";
                }
            }

            //
            // これ以降の書式設定が不要であることを伝えます。
            // (この値をfalseにした場合は、この後e.CellStyleプロパティの値を元に書式設定が行われます。)
            //
            e.FormattingApplied = true;
        }

        private object GetDataSource() {
            BindingSource source = new BindingSource();

            source.DataSource = typeof(SampleModel);

            source.Add(new SampleModel("1", "gsf_zero1"));
            source.Add(new SampleModel("2", "gsf_zero2"));
            source.Add(new SampleModel("illegalNumber", "gsf_zero3"));

            return source;
        }

        private void MainForm_Load(object sender, EventArgs e) {
            //
            // DataGridViewを構築します。
            //
            ConstructDataGridView();
        }
    }

    /// <summary>
    /// サンプル用のモデルクラスです。
    /// </summary>
    internal class SampleModel{
        string _id;
        string _name;

        public SampleModel(string id, string name){
            _id   = id;
            _name = name;
        }

        public string Id{
            get{
                return _id;
            }
            set{
                _id = value;
            }
        }

        public string Name{
            get{
                return _name;
            }
            set{
                _name = value;
            }
        }
    }
}


================================
過去の記事については、以下のページからご参照下さい。

サンプルコードは、以下の場所で公開しています。