问题
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.
回答1:
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
public partial class Form1 : Form
{
BindingSource bs = new BindingSource();
....
Then in the form constructor
public Form1()
{
filmlijst = new List<Film>();
bs.DataSource = filmlijst;
comboBox1.DataSource = bs;
}
finally add items to the BindingSource and not directly to your list
private void button1_Click(object sender, EventArgs e)
{
Film film = new Film(textBox1.Text);
bs.Add(film);
}
This is from the remark section of the docs about the BindingSource
The BindingSource component serves many purposes. First, it simplifies binding controls on a form to data by providing currency management, change notification, and other services between Windows Forms controls and data sources. This is accomplished by attaching the BindingSource component to your data source using the DataSource property.
回答2:
Try add this
private void button1_Click(object sender, EventArgs e) { Film film = new Film(textBox1.Text);
filmlijst.Add(film);
comboBox1.DataSource = null;
comboBox1.DataSource = filmlijst;
var comboboxItemCount = comboBox1.Items.Count;
int x = Convert.ToInt32(comboboxItemCount-1);
comboBox1.Text = comboBox1.Items[x].ToString();
}
来源:https://stackoverflow.com/questions/55290177/put-selected-combobox-item-into-label