示例一:向窗体添加一个按钮:


using System;
using System.Drawing;
using System.Windows.Forms;

namespace WindowsFormsApp33
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
//实例化一个命令按钮
Button btn = new Button();
//设置命令按钮的属性
btn.Location = new Point(50, 50);
btn.Size = new Size(80, 25);
btn.Text = "退出";
btn.Click += btn_Click;
//btn.Click += new System.EventHandler(this.btn_Click);
//添加到窗口的Controls集合中
this.Controls.Add(btn);
}
void btn_Click(object sender, EventArgs e)
{
this.Close();
}

}
}

btn.Click += new System.EventHandler(this.btn_Click);

和btn.Click += btn_Click;等价

示例二:态生成控件


using System;
using System.Drawing;
using System.Windows.Forms;

namespace WindowsFormsApp33
{
public partial class Form1 : Form
{
public Form1()

{
InitializeComponent();
}
private void Form1_Load(object sender, EventArgs e)
{
int row = 0;
for (int i = 0; i < 15; i++)
{
if (i % 5 == 0 && i != 0)
{
row++;
}
Button btn = new Button();
//控件名称
btn.Name = "mybutton" + i.ToString();
//控件显示文本
btn.Text = string.Format("按钮{0}", i + 1);
//控件大小
btn.Size = new Size(50, 50);
//控件位置【动态变化】
btn.Location = new Point(50 + i % 5 * 100, 50 + row * 100);
//添加到窗体
this.Controls.Add(btn);
}
}
}
}


C#用代码向窗体中添加控件?_控件



方法很多,只要创建后保留了对象的引用就行,比如说可以放在List里,或者也可以多建几个变量,比如象

List<Button> list = new List<Button>();

private void Form1_Load(object sender, EventArgs e)

{

for (int i = 0; i < 4; i++)

{

Button btn = new Button();

btn.Text = "xxx"+i;

//其它属性赋值

list.Add(btn);

}

}

之后你就可以通过list[2]这种来访问对应的button了,比如list[0].Text="aaa";