我尝试了很多版本,但大多数教程都是针对wpf应用程序的。 无论如何,我可以制作某种格子,但是有些按钮不在形状中,并且它们之间的空间太大(当然,如果我调整窗体大小,网格仍然是相同的大小)。
这是我的尝试,这是不正常的:
int size = 32;
_buttonGrid = new Button[size, size];
for (Int32 i = 0; i < size; i++)
for (Int32 j = 0; j < size; j++)
{
_buttonGrid[i, j] = new Button();
_buttonGrid[i, j].Location = new Point( size * j, size * i);
_buttonGrid[i, j].Size = new Size(flowLayoutPanel1.Width / size, flowLayoutPanel1.Height / size);
_buttonGrid[i, j].Font = new Font(FontFamily.GenericSansSerif, 6, FontStyle.Bold);
_buttonGrid[i, j].Enabled = true;
_buttonGrid[i, j].TabIndex = 10 + i * size + j;
_buttonGrid[i, j].FlatStyle = FlatStyle.Flat; stípus
flowLayoutPanel1.Controls.Add(_buttonGrid[i, j]);
}
答案 0 :(得分:3)
您可以对列和行使用TableLayoutPanel并将按钮放入其中。
例如,将TableLayoutPanel添加到表单中,并将此代码放在表单的Load事件中:
private void Form_Load(object sender, EventArgs e)
{
var rowCount = 10;
var columnCount = 10;
this.tableLayoutPanel1.ColumnCount = columnCount;
this.tableLayoutPanel1.RowCount = rowCount;
this.tableLayoutPanel1.ColumnStyles.Clear();
this.tableLayoutPanel1.RowStyles.Clear();
for (int i = 0; i < columnCount; i++)
{
this.tableLayoutPanel1.ColumnStyles.Add(new System.Windows.Forms.ColumnStyle(System.Windows.Forms.SizeType.Percent, 100 / columnCount ));
}
for (int i = 0; i < rowCount; i++)
{
this.tableLayoutPanel1.RowStyles.Add(new System.Windows.Forms.RowStyle(System.Windows.Forms.SizeType.Percent, 100 / rowCount ));
}
for (int i = 0; i < rowCount; i++)
{
for (int j = 0; j < columnCount; j++)
{
var button = new Button();
button.Text = string.Format("{0}{1}", i, j);
button.Name = string.Format("button_{0}{1}", i, j);
button.Dock = DockStyle.Fill;
this.tableLayoutPanel1.Controls.Add(button, j, i);
}
}
}