[求助]winform动态删除控件
通过CheckedListBox获得项,传给listbox,传过来几项就创建几个textboxfor (int i = 0; i < clb.CheckedItems.Count; i++)
{
lbx.Items.Add(clb.CheckedItems[i]);
}
//创建textbox
TextBox t1;
for (int c = 0; c < lbx.Items.Count; c++)
{
t1 = new TextBox();
t1.Text = "";
t1.Name = "";
this.flowLayoutPanel2.Controls.Add(t1);
}
但是现在如果又从新选择了项传给Listbox的话,textbox又会创建新的,而以前的不会销毁!
求各位易做图救命啊!!!
现在就是要把以前创建出来的删除! --------------------编程问答-------------------- 如下试试看:
foreach(Control ctr in this.flowLayoutPanel2.Controls)
{
if (ctr is TextBox)
{
this.flowLayoutPanel2.Controls.Remove(ctr);
}
}
--------------------编程问答-------------------- 把那个TextBox的引用从Controls中remove掉,然后调用它的Dispose()方法就行了. --------------------编程问答--------------------
lbx.Items.Clear();
for (int i = 0; i < clb.CheckedItems.Count; i++)
{
lbx.Items.Add(clb.CheckedItems[i]);
string txtName = "txt" + i.ToString();
if(this.flowLayoutPanel2.Controls.ContainsKey(txtName))continue;
TextBox t1 = new TextBox();
t1.Text = "";
t1.Name = txtName;
//t1...
this.flowLayoutPanel2.Controls.Add(t1);
}
这种方法只能避免重复创建TextBox.
还有种方法是:
--------------------编程问答-------------------- 如1楼所说,
lbx.Items.Clear();
this.flowLayoutPanel2.Controls.Clear();
for (int i = 0; i < clb.CheckedItems.Count; i++)
{
lbx.Items.Add(clb.CheckedItems[i]);
string txtName = "txt" + i.ToString();
TextBox t1 = new TextBox();
t1.Text = "";
t1.Name = txtName;
//t1...
this.flowLayoutPanel2.Controls.Add(t1);
}
将TextBox从flowLayoutPanel2中Remove掉。 --------------------编程问答-------------------- 3楼答的很完全了,补充一点,如果有做事件委托,请在remove的时候一并remove --------------------编程问答-------------------- 遍历-筛选-移除~
补充:.NET技术 , C#