方法1:
int i = 0;
List<PhoneTextBox> list = new List<PhoneTextBox>();
private void btnAdd_Click(object sender, EventArgs e)
{
if (i >= 9)//只能添加9个(看自己需求)
{
return;
}
else
{
i = i + 1;
PhoneTextBox txtPhone = new PhoneTextBox();
= "txtPhone" + i;
= new Poin, + + * (i - 1) + 4);
+= txtPhone_Click;
(txtPhone);
= new Point(.X, .Y + );
int n = ;
li(txtPhone);
//保证复制后的控件都在原控件下方显示
();
}
}
private void txtPhone_Click(object sender, EventArgs e)
{
Control c = (Control)sender;
string name = c.Parent.Name;
int nIndex = GetControlsName);
for (int n = nIndex + 1; n < li; n++)
{
list[n].Location = new Point(list[n].Loca, list[n].Loca - list[n].Height);
}
li(nIndex);
this. = new Point(this..X, this..Y - c.Height);
int b = c.Height;
);
BindClick(c);
i = i - 1;
}
//根据控件名称找控件索引
public int GetControlsName(string name)
{
int nIndex = 0;
for (int i = 0; i < li; i++)
{
if (list[i].Name == name)
{
nIndex = i;
break;
}
}
return nIndex;
}
//绑定删除控件事件的代码
private void BindClick(Control cl)
{
//保证如何在删除和添加时能释放资源(即可以紧跟在显示的控件后面显示)
cl.Con();
DisposeControls(cl);
//释放资源
cl.Dispose();
}
//在清空控件时如何释放资源
private void DisposeControls(Control cParent)
{
foreach (Control c in cParent.Controls)
{
//DisposeControls(c);
c.Con();
c.Dispose();
}
}
设计视图和运行结果如图
方法2:
在窗体加一个flowLayoutPanel1控件还有一个button按钮
private void btnadd_Click(object sender, EventArgs e)
{
string controlMark = Guid.NewGuid().ToString();
TextBox txt1 = new TextBox();
= "txt_" + controlMark;
= 120;
(txt1);
Button btnDel = new Button();
b = "del_" + controlMark;
b = "删除";
b += new EventHandler(delControl);
(btnDel);
}
///点击删除按钮删除生成的控件
public void delControl(object sender, EventArgs e)
{
Button btnAction = sender as Button;
string id = b('_')[1];
foreach (Control c in )
{
if == "txt_" + id)
{
(c);
}
}
foreach (Control c in )
{
if == "del_" + id)
{
(c);
}
}
}