Hello I am having an error and I can't figure it out. I am trying to select an object in my combobox and display the objects name into a label.
This is my class:
class Film
{
public string Naam { get; set; }
public Film(string naam)
{
Naam = naam;
}
public override string ToString()
{
return $"{Naam}";
}
}
And this is the code of my form
public partial class Form1 : Form
{
List<Film> filmlijst;
public Form1()
{
InitializeComponent();
filmlijst = new List<Film>();
}
private void button1_Click(object sender, EventArgs e)
{
Film film = new Film(textBox1.Text);
filmlijst.Add(film);
comboBox1.DataSource = null;
comboBox1.DataSource = filmlijst;
}
private void comboBox1_SelectedIndexChanged(object sender, EventArgs e)
{
label1.Text = ((Film)comboBox1.SelectedItem).Naam;
}
}
So I create an object of Film with a Textbox to give it a name. If I want to add multiple Films my combobox won't reload without this line of code :
comboBox1.DataSource = null;
Without this line of code I can see the name of my object in the TextLabel. But then I can't add more object because it doesn't reload.
You need to use a BindingSource to let the combo be aware of the changes to your list and when add items add them to the BindingSource
First declare the BindingSource variable at the class level
Then in the form constructor
finally add items to the BindingSource and not directly to your list
This is from the remark section of the docs about the BindingSource
Try add this
private void button1_Click(object sender, EventArgs e) { Film film = new Film(textBox1.Text);