所以场景是:UserControl
:1 GroupBox
里面:2 combobox
,1 textbox
,1 richtextbox
和1 button
为“删除groupBox”
形式:1个按钮(添加groupBox
)和flowLayoutPanel
我的问题:我可以添加尽可能多的groupBox
组件,但当我单击“删除组框”按钮时,如果我执行“表单1”:
FlowLayoutPanel.Dispose()
我删除了所有创建的GroupBox
组件,如果我这样做,则删除userControl
:
GroupBox.Dispose();
它删除了它,但是当我添加另一个时,它会在“被删除的那个”之下
这是我正在使用的代码:
用户控件:
private void Remove_Click(object sender, EventArgs e)
{
removeFunction();
}
表格1:
Private void add_GroupBox(my class)
{
myclass myClass = new myclass(datasource, null);
flowLayoutPanel.Controls.add(myClass);
}
private void Remove_GroupBox()
{
flowLayoutPanel.Controls.Clear(); // I know it removes all the groups created
FlowLayoutPanel.Dispose(); // It does the same job
// I just want the get the selected groupBox and dispose it or clear it
}
您有两种选择:
你可以在你的User Control
上添加一个按钮来处理它自己。
this.Dispose();
您可以向表单添加属性以跟踪选定的用户控件。
Form1中:
public Control SelectedItem { get; set; } = null;
private void DeleteButton_Click(object sender, EventArgs e)
{
if (SelectedItem != null)
{
SelectedItem.Dispose();
}
}
的UserControl1:
// You can use any Event you prefer (Enter, Click or etc.).
private void GroupBox1_Enter(object sender, EventArgs e)
{
// First Parent is FlowLayoutPanel
// Second Parent is your Form
Form1 parent = this.Parent.Parent as Form1;
if (parent != null)
{
parent.SelectedItem = this;
}
}