public Form1()
{
InitializeComponent();
int top = 5;
int left = 5;
for (int i = 0; i < 10; i++)
{
Button button = new Button();
button.Height = 50;
button.Left = left;
button.Top = top;
this.Controls.Add(button);
left += button.Width + 2;
}
}
public Form1()
{
InitializeComponent();
for (int i = 0; i < 10; i++)
{
Button button = new Button();
button.Height = 50;
FlowLayoutPanel1.Controls.Add(button); //panel handles Left/Top location
}
}
该面板还具有帮助您的应用扩展到不同dpi或屏幕/窗口大小的优势.
其中任何一个也可以适应开始考虑连接到数据源(并减少代码):
var buttons = Enumerable.Range(0, 10).Select(b => new Button {
Height = 50,
Left = 5 + ( b * (BUTTONWIDTH + 2) ),
Top = 5,
Name = String.Format("Button{0}", b)
});
//buttons.ToList()
//or
//this.Controls.AddRange(buttons.ToArray())
//or
//FlowLayoutPanel1.Controls.AddRange(buttons.ToArray()) //Remove Left/Top code
但是所有这一切都没有意义,直到你可以让按钮实际做某事.您需要(至少)Click事件的事件处理程序:
foreach (var b in butons)
{
b.Click += (s,e) =>
{
//click code for all of the buttons goes here
// you can tell the buttons apart by looking at the "s" variable
};
}