いろいろ備忘録日記

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

TableLayoutPanelのサンプル (System.Windows.Forms.TableLayoutPanel)


めっちゃ久しぶりにTableLayoutPanelを使ったら、使い方完全に忘れていたのでメモメモ。
基本最近はDevExpressのLayoutControlしか使っていなかった・・・。


以下、思い出し用のサンプル.

// vim:set ts=4 sw=4 et ws is nowrap ft=cs:
using System;
using System.Data;
using System.Diagnostics;
using System.Drawing;
using System.Linq;
using System.Windows.Forms;

namespace Samples {

    public class TableLayoutSample  : Form {

        TableLayoutPanel _tlpMain;

        public TableLayoutSample() {
            InitializeComponent();
        }

        private void InitializeComponent() {

            Size = new Size(400, 200);
            StartPosition = FormStartPosition.CenterScreen;
            Text = "TableLayoutPanelのサンプル";

            SuspendLayout();

            _tlpMain = new TableLayoutPanel();
            _tlpMain.Dock = DockStyle.Fill;

            InitializeLayoutPanel();

            Controls.Add(_tlpMain);

            ResumeLayout();
        }

        private void InitializeLayoutPanel() {
            Debug.Assert(_tlpMain != null);

            //
            // 5x4のレイアウトを作成.
            //
            _tlpMain.ColumnCount = 5;
            _tlpMain.RowCount    = 5;

            //
            // 全体設定.
            //
            _tlpMain.CellBorderStyle = TableLayoutPanelCellBorderStyle.Single;
            _tlpMain.GrowStyle       = TableLayoutPanelGrowStyle.AddColumns;


            //
            // 各列の幅を設定.
            //
            foreach(ColumnStyle style in _tlpMain.ColumnStyles) {
                style.SizeType = SizeType.Percent;
                style.Width    = 20;
            }

            foreach(RowStyle style in _tlpMain.RowStyles) {
                style.SizeType = SizeType.AutoSize;
                style.Height   = 20;
            }
            
            //
            // 各セルにコントロールを設定.
            //
            for(int rowIndex = 0; rowIndex < _tlpMain.RowCount; rowIndex++) {

                for(int colIndex = 0; colIndex <  _tlpMain.ColumnCount; colIndex++) {
                    
                    _tlpMain.Controls.Add(new Label{ Text = string.Format("CELL={0}, {1}", rowIndex, colIndex), Dock = DockStyle.Fill }, colIndex, rowIndex);
                }
            }

            //
            // ColSpan, RowSpanの設定.
            //
            _tlpMain.SetColumnSpan(_tlpMain.GetControlFromPosition(0, 0), 2);
            _tlpMain.SetRowSpan(_tlpMain.GetControlFromPosition(0, 2), 2);

        }

        [STAThread]
        static void Main() {
            Application.EnableVisualStyles();
            Application.Run(new TableLayoutSample());
        }
    }
}