ComboBox不加载用户

时间:2010-10-29 12:42:04

标签: c# winforms datasource

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();
    }            
}

我希望每次保存后组合框都会显示一个用户列表。因此,有人创建了一个新用户,它应该在之后显示在组合框中。这不起作用,没有添加新用户,只有初始“加载”似乎有效。

1 个答案:

答案 0 :(得分:1)

  

复杂DataBinding接受IList或IListSource作为数据源。

private void LoadUsersToComboBox()
{
    // comboBox1.DataSource = null; // No need for this

    comboBox1.DataSource = peopleRepo.FindAllPeople().ToList(); /*Returns IQueryable<People>*/
}

不要重新分配DisplayMember&amp; amp; ValueMember每次刷新,只需一次,

public Form1()
{
    InitializeComponent();

    comboBox1.DisplayMember = "Name";
    comboBox1.ValueMember = "ID";
    LoadUsersToComboBox()
}
祝你好运!