public Form1()
{
InitializeComponent();
comboBox1.DisplayMember = "Name";
comboBox1.ValueMember = "ID";
LoadUsersToComboBox();
}
PersonRepository peopleRepo = new PersonRepository();
private void LoadUsersToComboBox()
{
comboBox1.DataSource = peopleRepo.FindAllPeople().ToList();
}
private void button2_Click(object sender, EventArgs e)
{
LoadUsersToComboBox();
}
此方法将首次加载一个值仅的组合框,但不会在后续尝试中加载:
private void LoadUsersToComboBox()
{
comboBox1.DataSource = peopleRepo.FindAllPeople(); /*Return IQueryable<Person>*/
}
每次调用LoadUsersToComboBox()时都会加载:
private void LoadUsersToComboBox()
{
comboBox1.DataSource = peopleRepo.FindAllPeople().ToList();
}
为什么第一次只加载第一次?
以下是PeopleRepository类的代码:
namespace SQLite_Testing_Grounds
{
public class PersonRepository
{
private ScansEntities3 db = new ScansEntities3();
public IQueryable<Person> FindAllPeople()
{
return db.People;
}
}
}
答案 0 :(得分:2)
解决方案很简单:
// This method returns the same reference every time
public IQueryable<Person> FindAllPeople()
{
return db.People;
}
结果:
// Nothing changes, DataSource old value is still the same (same reference,
// even is the content of the People list does change).
comboBox1.DataSource = peopleRepo.FindAllPeople();
// ToList() creates a new object each time, so DataSource is assigned to a
// NEW object, and so calls a kind of invalidation of its visual.
comboBox1.DataSource = peopleRepo.FindAllPeople().ToList();
。
这是一个数据绑定的基础,实际上我根本不是一个WinForms人(我对WPF了解得更多),但我认为在内部,你有一些类似的东西:
private object dataSource;
public object DataSource {
get {
if (value != dataSource) {
dataSource = value;
RaisePropertyChanged("DataSource");
}
}
}
答案 1 :(得分:0)
在此调用中,您要设置数据源,而不是数据绑定调用以实际绑定数据。你能发布调用.databind吗?
的方法