I got this answer here: https://stackoverflow.com/questions/15902299/selecting-an-item-in-a-listbox-to-assign-it-as-a-temp-variable
Suppose you have loaded the lisBox1
with objects of type Genre
.
lisBox1.Datasource = this.GetAllGenresFromTextFiles();
lisBox1.DisplayMember = "Genre";
Add an event to SelectionChanged
of your lstBox1
:
lstBox1.SelectionChanged += lstBox1_SelectionChanged;
And then in this event, filter the data for listbox2 :
void lstBox1_SelectionChanged(object sender, EventArgs e)
{
var movies = m_allMovies;
var genre = lstBox1.SelectedItem as Genre;
if(genre != null)
{
movies = movies.Where(m => m.Genre == genre.Genre).ToList();
}
lstbox2.Datasource = movies;
}
m_allMovies
is a list of all the movies you have loaded from your textfiles.
You can also read your text file every time the user clicked a different genre, it will consume less memory but more CPU:
void lstBox1_SelectionChanged(object sender, EventArgs e)
{
var movies = this.GetAllMoviesFromTextFiles();
var genre = lstBox1.SelectedItem as Genre;
if(genre != null)
{
movies = movies.Where(m => m.Genre == genre.Genre).ToList();
}
lstbox2.Datasource = movies;
}
The keypoint here is not to filter row from the Listbox
. You must think of it as your Listbox
contains a subset of all your movies.
And each time you want to add or remove rows from a Listbox
, in fact you are reloading it with appropriate datas.
and my problem is this:
With the first 2 lines of code (At the top of the answer), where would i place this (I'm new to C# so .Datasource
& DisplayMember
are new things to me). Also where you have "this.GetAllGenresFromTextFiles" (and the same for var movies = this.GetAllMoviesFromTextFiles)
--> would i place the location of my text file within the brackets?