更改ComboBox中一个项目的文本

时间:2016-12-26 20:06:22

标签: c# .net winforms

我有一个ComboBox,其中包含一个名称列表:LastName + ", " + FirstName

选择名称后,它会分别使用First和Last名称填充两个文本框。

我想要做的是,如果在文本框中更改了名称,我希望将更改更新到ComboBox,而无需重新加载整个内容。我的ComboBox没有直接从数据库加载,因此我无法使用RefreshItem()

这甚至可能吗?

1 个答案:

答案 0 :(得分:1)

您可以实现INotifyPropertyChanged接口并使用BindingSource作为ComboBox的DataContext。请参阅以下示例代码。

<强> Person.cs:

public class Person : INotifyPropertyChanged
{
    private string _firstName;
    public string FirstName
    {
        get { return _firstName; }
        set { _firstName = value; NotifyPropertyChanged(); }
    }

    private string _lastName;
    public string LastName
    {
        get { return _lastName; }
        set { _lastName = value; NotifyPropertyChanged(); }
    }

    public string FullName { get { return LastName + ", " + FirstName; } }

    public event PropertyChangedEventHandler PropertyChanged;
    private void NotifyPropertyChanged([CallerMemberName] String propertyName = "")
    {
        if (PropertyChanged != null)
            PropertyChanged(this, new PropertyChangedEventArgs(propertyName));
    }
}

<强> Form1.cs中:

public partial class Form1 : Form
{
    public Form1()
    {
        InitializeComponent();

        List<Person> people = new List<Person>()
            {
                new Person() { FirstName = "Donald", LastName = "Duck" },
                new Person() { FirstName = "Mickey", LastName = "Mouse" }
            };
        BindingSource bs = new BindingSource();
        bs.DataSource = people;
        comboBox1.DataSource = bs;
        comboBox1.DisplayMember = "FullName";

        textBox1.DataBindings.Add(new Binding("Text", bs, "FirstName", false, DataSourceUpdateMode.OnPropertyChanged));
        textBox2.DataBindings.Add(new Binding("Text", bs, "LastName", false, DataSourceUpdateMode.OnPropertyChanged));

    }
}