LoginSignup
1
1

More than 1 year has passed since last update.

WinFormsのTableLayoutPanelの行数列数をコードで動的に増減する際の注意点

Posted at

前提

  • WinFormsでTableLayoutPanelを使っていて行数列数を動的に変更させたい人向け
  • 私が引っかかったので共有

やりたいこと

Winformsで手軽に均等分割などができるコントロールであるTableLayoutPanel。
その行数列数をコードで動的に増減したい。
今回は3x3と2x2のレイアウトをトグルで切り替える。

均等分割ならパーセントで50%と33.333%あたりを入れ替えればいいだろう。

ん?
TableLayoutPanelにColumnCount, RowCountというset可能なプロパティが有るぞ。
→よしせっかくなのでついでにこいつにも列数行数を代入してみよう。

private void ToggleLayout()
{
	IsQuarterLayout = !IsQuarterLayout;
	const float half = 50f;
	const float thirds = 33.333f;
	var count = IsQuarterLayout ? 2 : 3;
	tableLayoutPanel.ColumnCount = count;
	tableLayoutPanel.RowCount = count;
	tableLayoutPanel.ColumnStyles[0] = new ColumnStyle(SizeType.Percent, IsQuarterLayout ? half : thirds);
	tableLayoutPanel.ColumnStyles[1] = new ColumnStyle(SizeType.Percent, IsQuarterLayout ? half : thirds);
	tableLayoutPanel.ColumnStyles[2] = new ColumnStyle(SizeType.Percent, IsQuarterLayout ? 0 : thirds);
	tableLayoutPanel.RowStyles[0] = new RowStyle(SizeType.Percent, IsQuarterLayout ? half : thirds);
	tableLayoutPanel.RowStyles[1] = new RowStyle(SizeType.Percent, IsQuarterLayout ? half : thirds);
	tableLayoutPanel.RowStyles[2] = new RowStyle(SizeType.Percent, IsQuarterLayout ? 0 : thirds);
}

cap.gif

一見うまくいったように見えるが、ウィンドウを縦に伸ばし一定の高さを超えると謎の行が下に現れる。

は?

解決方法

ColumnCount, RowCountには代入してはいけない。

private void ToggleLayout()
{
	IsQuarterLayout = !IsQuarterLayout;
	const float half = 50f;
	const float thirds = 33.333f;
	tableLayoutPanel.ColumnStyles[0] = new ColumnStyle(SizeType.Percent, IsQuarterLayout ? half : thirds);
	tableLayoutPanel.ColumnStyles[1] = new ColumnStyle(SizeType.Percent, IsQuarterLayout ? half : thirds);
	tableLayoutPanel.ColumnStyles[2] = new ColumnStyle(SizeType.Percent, IsQuarterLayout ? 0 : thirds);
	tableLayoutPanel.RowStyles[0] = new RowStyle(SizeType.Percent, IsQuarterLayout ? half : thirds);
	tableLayoutPanel.RowStyles[1] = new RowStyle(SizeType.Percent, IsQuarterLayout ? half : thirds);
	tableLayoutPanel.RowStyles[2] = new RowStyle(SizeType.Percent, IsQuarterLayout ? 0 : thirds);
}

cap2.gif
これで縦に伸ばしても謎の行が表示されたりはしない。

教訓

なんかそれっぽい名前だからといってよく分からないプロパティに代入してはいけない。

1
1
1

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
1
1