简体   繁体   中英

Remove user control itself from the collection of flowlayout panel

I made a user control consist of 1 picture box,linklabel caption with "title" and two buttons caption with "view" and "remove" and it look like this

now I used this user control to add on the flowlayout panel now my question is How do I delete the user control itself by clicking the button "Remove" in order to remove itself from the flowlayout panel? I know it has something to do with flowLayoutPanel1.Controls.Remove(); or .RemoveAt(); btw I'm using C# visual Studio 2013,It would be grateful if someone could give me atleast a sample codes for this one.

my code for adding a user control is this one

private void add_Click(object sender, EventArgs e)<br>
{         
     AddItem add = new AddItem();          
     flowLayoutPanel1.Controls.Add(add);                   
}

This works for me:

private void removeButton_Click(object sender, EventArgs e)
{
    // if the images come from unmanged GDI bitmaps
    if (this.yourPictureBox.Image != null) this.pb_yourPictureBox.Image.Dispose();
    this.Parent.Controls.Remove(this);
}

This should go into the click event of that Button in your UserControl class.

Update:

I have by now gotten into the habit of making it even a bit more secure:

private void removeButton_Click(object sender, EventArgs e)
{
    // if the images come from unmanged GDI bitmaps
    if (this.yourPictureBox.Image != null) 
    {
        Image img = pb_yourPictureBox.Image;
        this.pb_yourPictureBox.Image = null;
        img .Dispose();
    }
    this.Parent.Controls.Remove(this);
}

This way the PictureBox will never try to show a disposed Image and crash, even if that could only happen for a virtually zero timespan..

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM