动态按钮创建和放大器;将它们放置在一个predefined以便使用C# [英] Dynamic button creation & placing them in a predefined order using c#
问题描述
NET 4.5 C#创建一个Windows窗体。我要动态地创建和放大器;添加按钮和放大器;也为它们分配单击事件,但希望他们能够动态地放置在一个特殊的方式,就像图像
NET 4.5 C# to create a windows form. I want to dynamically create & add buttons & also assign them click events but want them to be dynamically placed in a particular fashion just like the image
我的问题是如何动态地放置按钮以上述方式,即4×4格式(4个按键成一排,4列,但无限行)。是有可能在Win形式这样做?
My question is how do i place the buttons dynamically in the above fashion i.e. 4x4 format (4 buttons in a row, 4 columns but unlimited rows).Is it possible to do so in win forms??.
presently我试图下面提到的code,但有没有明确的想法,我如何放置按钮如上图
Presently i'm trying the below mentioned code but having no clear idea as to how do i place the buttons as shown above
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;
// ...
}
}
}
请指教与codeS的解决方案。先谢谢了。
Please advise solution with codes. Thanks in advance.
推荐答案
您可以使用的 TableLayoutPanel中
,并动态地创建按钮并将其添加到面板。
You can use a TableLayoutPanel
and create your buttons dynamically and add them to the panel.
例如:
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(控制)
,我们可以按顺序将控件添加到面板。 - 使用
TableLayoutPanel中。 Controls.Add被(控制,参数:columnIndex和rowIndex)
我们可以在特定的细胞中添加控件。
- Using
TableLayoutPanel.Controls.Add(control)
we can add controls sequentially to the panel. - Using
TableLayoutPanel.Controls.Add(control, columnIndex, rowIndex)
we can add controls at specific cells.
这篇关于动态按钮创建和放大器;将它们放置在一个predefined以便使用C#的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!