Kees van V. Kees van V. - 1 month ago 17
C# Question

C# Search controls in a FlowLayoutPanel

So I have a

FlowLayoutPanel
in my Windows Forms Application, which I use for storing movie fanarts and titles, now what I am looking for is a method to search for existing items in the
FlowLayoutPanel
. This is my GUI:

GUI Screenshot

In the
Search movies...
box, I want the
TextChanged
event to show only movies with the movie labels related to the search input.

Answer
foreach (Control c in myFlowLayoutPanel.Controls)
{
    if (!c.Property.Text.ToLower().Contains(searchBox.Text.ToLower()))
    {
        myFlowLayoutPanel.Controls.Remove(c);
    }
}

This will loop through the children of the panel - you can check some property against the search term and remove the child if it doesn't contain the search term.

EDIT: Based on your comment, it looks like you are getting matches only on your labels, so your pictures are going away. The way that I would approach that is to create a UserControl that holds both the image and a label (Right-click your project - Add - UserControl - give it a name). Use the designer to add a PictureBox and a Label (or whatever controls you are already using). Your code behind for the UserControl would look something like this:

public partial class Movie : UserControl
{
    public string Title { get; set; } // for easy matching

    public Movie()
    {
        InitializeComponent();
    }

    public Movie(Image thumbnail, string title) // use this constructor to make your movie tiles
    {
        InitializeComponent();
        pictureBox1.Image = thumbnail;
        label1.Text = title;
        Title = title;
    }
}

For each movie, you can create an instance of your new custom UserControl by passing in the thumbnail image and the title and then add the entire UserControl to your FlowLayoutPanel. Now you can keep or remove the entire UserControl depending on whether the Title property matches. Your foreach loop changes to this:

foreach (Control c in flp.Controls)
{
    // Check if the control is one of your custom UserControls:
    if (c.GetType() == typeof(Movie))
    {
        // since it is a "Movie", it is safe to cast it:
        Movie movie = (Movie)c;
        if (!movie.Title.ToLower().Contains(searchBox.Text.ToLower()))
        {
            flp.Controls.Remove(c); // remove or keep both the image and text
        }
    }
}