[英]Changing text of one item in a ComboBox
我有一个ComboBox,其中包含名称列表: LastName + ", " + FirstName
。
选择名称后,它将分别用名字和姓氏填充两个文本框。
我想做的是,如果在文本框中更改了名称,则我希望更改也可以更新到ComboBox,而不必重新加载整个内容。 我的ComboBox不是直接从数据库加载的,所以我不能使用RefreshItem()
这有可能吗?
您可以实现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));
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.