いろいろ備忘録日記

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

DataGridView入門記-12 (行にバインドされているオブジェクトの取得)(DataBoundItem)


行に紐付いているデータをイベント時などに取得するには、以下のプロパティを使用します。

DataGridViewRow.DataBoundItem

DataGridViewからは以下のようにしてアクセスします。

DataGridView.Rows[indexもしくは名前].DataBoundItem

戻り値は、objectなのでキャストもしくはasを指定して利用します。


以下サンプルです。

// vim:set ts=4 sw=4 et ws is nowrap ft=cs:

using System;
using System.Drawing;
using System.Windows.Forms;

using Gsf.Samples.Utility;

namespace Gsf.Samples.DGV{

    /// <summary>
    /// DataGridViewのDataBoundItemプロパティのサンプルです。
    /// </summary>
    /// <remarks>
    /// DataGridViewオブジェクトのDataGridViewRowオブジェクトに
    /// 定義されているDataBoundItemプロパティを使用すると行にバインドされている
    /// オブジェクトを取得できます。
    /// 以下のようにして使用します。
    ///
    /// Sample boundItem = grid.Rows[e.RowIndex].DataBoundItem as Sample;
    /// </remarks>
    public class DataGridViewSample12 : BaseForm{

        public DataGridViewSample12() : base("Gsf.Samples.DGV.DataGridSample12"){
            // nop;
        }

        protected override void InitializeComponents(){
            DataGridView grid = new DataGridView();

            grid.Dock                = DockStyle.Fill;
            grid.AutoGenerateColumns = true;
            grid.DataSource          = GetDataSource();
            grid.AllowUserToAddRows  = false;

            grid.CellClick += delegate(object sender, DataGridViewCellEventArgs e){
                DataGridView g = sender as DataGridView;

                //
                // 行に紐付いているオブジェクトを取得
                //
                Sample boundItem = g.Rows[e.RowIndex].DataBoundItem as Sample;
                if(boundItem != null){

                    MessageBox.Show(boundItem.ToString(), "行のデータ");

                    //
                    // テストとしてAgeに10を足していく
                    //
                    boundItem.Age += 10;

                    //
                    // データを変更した行のみ再描画
                    //
                    g.InvalidateRow(e.RowIndex);
                }
            };

            Controls.Add(grid);

            Size = new Size(400, 200);

            Load += delegate(object sender, EventArgs e){
                foreach(DataGridViewColumn col in grid.Columns){
                    col.ReadOnly = true;
                }
            };

        }

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

            source.DataSource = typeof(Sample);
            
            source.Add(new Sample(1, "gsf_zero1", 20));
            source.Add(new Sample(2, "gsf_zero2", 30));
            source.Add(new Sample(3, "gsf_zero3", 40));

            return source;
        }

        [STAThread]
        static void Main(){
            ApplicationUtility.Launch("Gsf.Samples.DGV.DataGridViewSample12");
        }
    }

    class Sample{
        int?   _id;
        string _name;
        int?   _age;

        public Sample(int? id, string name, int? age){
            _id   = id;
            _name = name;
            _age  = age;
        }

        public int? Id{
            get{
                return _id;
            }
            set{
                _id = value;
            }
        }

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

        public int? Age{
            get{
                return _age;
            }
            set{
                _age = value;
            }
        }

        public override string ToString(){
            return string.Format("id={0}, name={1}, age={2}", _id, _name, _age);
        }
    }
}

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

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