Populate Combobox from a list
There's one issue with visual controls updating (such as ComboBox etc): you'd rather prevent them from re-painting at each data change (at each item addition in your case):
cmbMovieListingBox.BeginUpdate(); // <- Stop painting
try {
// Adding new items into the cmbMovieListingBox
foreach(var item in LoadListings())
cmbMovieListingBox.Items.Add(item.GetFilmTitle());
finally {
cmbMovieListingBox.EndUpdate(); // <- Finally, repaint if required
}
Remove the {get; set;}
from the list declaration. It's not needed there.
Define your class like this:
public class Listing
{
private String filmTitle {get; set;}
private String description {get; set;};
…
}
On the form load event set the ComboBox
DisplayMember
and ValueMember
to "filmTitle"
cmbMovieListingBox.DisplayMember = "filmTitle";
cmbMovieListingBox.ValueMember = "filmTitle"
Finally, you must set the DataSource
of the ComboBox
to the list
cmbMovieListingBox.DataSource = films;
And there you have it. The rest of your code should function now.
if you are asking what i think you are asking, you need something like this in your form load:
foreach(Listing listing in LoadListings()){
cmbMovieListingBox.Items.Add(listing.GetFilmTitle());
}
I would hold List<Listing>
at the class level so you can access it when a user clicks on it. I would also throw this on it's own thread and not directly in the Load event. If it's a long process you will hang the ui.
private List<Listing> films { get; set; }
Load
films = LoadListings();
foreach (Listing film in films)
{
cmbMovieListingBox.Items.Add(film.GetFilmTitle());
}
When the user selects the item
Listing film = films.Where(f => f.GetFilmTitle().Equals(cmbMovieListingBox.SelectedValue)).FistOrDefault();
if (film != null)
{
//do work
}