いろいろ備忘録日記

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

DataGridView入門記-04 (現在のセルの値の取得(CurrentCell))

グリッド内で、現在のセルの値を取得するには以下のプロパティを使用します。

DataGridView.CurrentCell

まんまですね。w
でも、こういうのを普通に用意してくれているのが.netのいい所だと思います。
(いい意味で現実的な設計になっている)
JTableで同じことするのは、もうちょっと大変だったと思いますので。(^_^;;
取得できるオブジェクトは、DataGridViewCellオブジェクトとなります。


以下、サンプルです。
現在フォーカスが当たっているセルの情報を、ステータスバーに表示します。

// 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{

    public class DataGridViewSample04 : BaseForm{

        public DataGridViewSample04() : base("DataGridViewSample04"){
            // nop;
        }

        protected override void InitializeComponents(){
            SuspendLayout();

            DataGridView grid = CreateDefaultGrid();

            grid.Dock               = DockStyle.Fill;
            grid.AllowUserToAddRows = false;

            grid.AlternatingRowsDefaultCellStyle.BackColor = Color.LightBlue;

            PutTestData(grid);

            //
            // 読み取り専用に.
            //
            foreach(DataGridViewColumn column in grid.Columns){
                column.ReadOnly = true;
            }

            //
            // データ確認用のステータスバー生成.
            //
            StatusStrip statusBar = new StatusStrip();

            ToolStripStatusLabel statusLabel = new ToolStripStatusLabel();
            statusLabel.Spring    = true;
            statusLabel.TextAlign = ContentAlignment.MiddleLeft;

            statusBar.Items.Add(statusLabel);

            //
            // イベントを設定.
            //
            grid.CellEnter += delegate(object sender, DataGridViewCellEventArgs e){
                //
                // 現在フォーカスがあるセルの情報をステータスバーに表示.
                //
                DataGridViewCell cell = grid.CurrentCell;

                statusLabel.Text 
                    = string.Format("行:{0}, 列:{1}, 値:{2}", (cell.RowIndex + 1), (cell.ColumnIndex + 1), cell.Value);

            };
            
            Controls.Add(grid);
            Controls.Add(statusBar);

            ResumeLayout();
        }

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

}


サンプルは以下の場所から落とせます。
サンプル



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

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