C#从父容器和List中删除控件

时间:2016-03-23 08:50:01

标签: c# forms winforms user-controls

我有2个继承UserControl的控件 一个是容器,另一个是基本文本框标签的集合,由此标记为ContainerControlComboControl

ContainerControl包含List<ComboControl>和foreach循环,可将其添加到FlowLayoutPanelComboControl有一个按钮,我希望用它从父母的列表中清除自己。

我不确定这样做的最佳方法是什么。 this.parent并投放到ContainerControlDispose()工作?我很确定我可以将引用传递给List,但这听起来不必要地混乱......

 public partial class ContainerControl : UserControl
 {
    List<ComboControl> ComboControls = new List<ComboControl>();
    ...
    //procederaly generate and fill ComboControls here
    ...
    foreach (ComboControl value in ComboControls)
    {
        this.flowLayoutTable.Controls.Add(value);
    }
 ...
 }

 public partial class ComboControl : UserControl
 {
     private void BtnDel_Click(object sender, EventArgs e)
    {
        //what goes here
    }
 ...
 }

2 个答案:

答案 0 :(得分:2)

按照Zohar Peled所说的内容,删除控件以避免资源泄漏。

private void cleanup(Control c)
{          
    foreach(Control child in c.Controls)        
        cleanup(child);         

    if (c.Parent != null)
    {
        c.Parent.Controls.Remove(c);
        c.Dispose();
    }
}

答案 1 :(得分:0)

对于这样的场景,我会使用自定义事件向父控件发送删除请求:

您的ComboControl与自定义事件:

 //Create Custom Event
    public delegate void DeleteControlDelegate(object sender);

    public partial class ComboControl : UserControl
    {
        //Custom Event to send Delete request
        public event DeleteControlDelegate DeleteControlDelegate;

        public ComboControl()
        {
            InitializeComponent();
        }

        //Invoke Custom Event
        private void OnDeleteControl(object sender)
        {
            DeleteControlDelegate?.Invoke(sender);
        }

        private void BtnDel_Click(object sender, EventArgs e)
        {
            //On ButtonClick send Delete request
           OnDeleteControl(this);
        }
    }

并在您的ContainerControl中订阅每个ComboControl的事件:

List<ComboControl> _comboControls = new List<ComboControl>();

        public ContainerControl()
        {
            InitializeComponent();
        }

        private void ContainerControl_Load(object sender, EventArgs e)
        {
            _comboControls.Add(new ComboControl());
            _comboControls.Add(new ComboControl());
            _comboControls.Add(new ComboControl());

            foreach (ComboControl value in _comboControls)
            {
                flowLayoutPanel.Controls.Add(value);
                //Subscribe to Custom Event here
                value.DeleteControlDelegate += Value_DeleteControlDelegate;
            }
        }

        private void Value_DeleteControlDelegate(object sender)
        {
            //When Raised Delete ComboControl
            flowLayoutPanel.Controls.Remove((Control) sender);
        }
    }