创建动态按钮并使用c#将它们置于预定义的顺序中

NET 4.5 C#创建一个Windows窗体。 我想动态创建和添加按钮并为它们分配点击事件,但希望它们像图像一样以特定方式动态放置。

在此处输入图像描述

我的问题是如何以上述方式动态放置按钮,即4×4格式(连续4个按钮,4列但无限行)。 是否有可能以胜利forms这样做?

现在我正在尝试下面提到的代码,但是我不知道如何放置如上所示的按钮。

public Form1() { InitializeComponent(); for (int i = 0; i < 5; i++) { Button button = new Button(); button.Location = new Point(160, 30 * i + 10); button.Click += new EventHandler(ButtonClickCommonEvent); button.Tag = i; this.Controls.Add(button); } } void ButtonClickCommonEvent(object sender, EventArgs e) { Button button = sender as Button; if (button != null) { switch ((int)button.Tag) { case 0: // First Button Clicked break; case 1: // Second Button Clicked break; // ... } } } 

请用代码告知解决方案。

您可以使用TableLayoutPanel动态创建按钮并将其添加到面板中。

例如:

 private void Form1_Load(object sender, EventArgs e) { var rowCount = 3; var columnCount = 4; 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* columnCount; i++) { var b = new Button(); b.Text = (i+1).ToString(); b.Name = string.Format("b_{0}", i + 1); b.Click += b_Click; b.Dock = DockStyle.Fill; this.tableLayoutPanel1.Controls.Add(b); } } void b_Click(object sender, EventArgs e) { var b = sender as Button; if (b != null) MessageBox.Show(string.Format("{0} Clicked", b.Text)); } 

在此处输入图像描述

注意:

  • 使用TableLayoutPanel.Controls.Add(control)我们可以按顺序向面板添加控件。
  • 使用TableLayoutPanel.Controls.Add(control, columnIndex, rowIndex)我们可以在特定单元格中添加控件。