问题
private void LoadUsersToComboBox()
{
comboBox1.DataSource = null;
comboBox1.DataSource = peopleRepo.FindAllPeople(); /*Returns IQueryable<People>*/
comboBox1.DisplayMember = "Name";
comboBox1.ValueMember = "ID";
}
private void button2_Click(object sender, EventArgs e)
{
CreateNewPerson();
LoadUsersToComboBox();
}
private void CreateNewPerson()
{
if (textBox2.Text != String.Empty)
{
Person user = new Person()
{
Name = textBox2.Text
};
peopleRepo.Add(user);
peopleRepo.Save();
}
}
I'd like the combobox to display a list of users, after every save. So, someone creates a new user and it should display in the combobox right after that. This isn't working, no new users are added, only the initial 'load' seems to work.
回答1:
Complex DataBinding accepts as a data source either an IList or an IListSource.
private void LoadUsersToComboBox()
{
// comboBox1.DataSource = null; // No need for this
comboBox1.DataSource = peopleRepo.FindAllPeople().ToList(); /*Returns IQueryable<People>*/
}
Don't reassign the DisplayMember & The ValueMember every refresh, just once,
public Form1()
{
InitializeComponent();
comboBox1.DisplayMember = "Name";
comboBox1.ValueMember = "ID";
LoadUsersToComboBox()
}
Good luck!
来源:https://stackoverflow.com/questions/4051939/combobox-doesnt-load-users