[英]Binding combobox
I have done a search for this, however i believe i want to achieve something slightly different. 我已经对此进行了搜索,但是我相信我想要实现一些稍微不同的东西。
I have a combobox which is setup to statically contain 3 items for example, Person1, Person2, Person3. 我有一个组合框,其设置为静态包含3个项目,例如Person1,Person2,Person3。
I then have an object, for example called Person. 然后,我有一个对象,例如,称为“人”。 This object will contain a property called PersonType, which maybe Person3.
该对象将包含一个名为PersonType的属性,可能是Person3。 What I want to do, is bind that Person object to the combo box, and on load, the combobox should highlight person3 as the selected item.
我想做的是将该Person对象绑定到组合框,并且在加载时,组合框应突出显示person3作为所选项目。 How could I go about doing this please?
我该怎么做呢? I want it to be bound two-way as the rest of my controls.
我希望将它与其他控件绑定在一起。
public class Person : INotifyPropertyChanged
{
public event PropertyChangedEventHandler PropertyChanged;
private string _PersonType;
public string PersonType
{
get { return _PersonType; }
set
{
_Description = value;
NotifyPropertyChanged("PersonType");
}
}
public void NotifyPropertyChanged(string name)
{
if (PropertyChanged != null)
{
PropertyChanged(this, new PropertyChangedEventArgs(name));
}
}
}
以下应该工作:
ddlPerson.SelectedItem = objPerson.PersonType;
The follow code should achieve your goal. 以下代码应该可以实现您的目标。 I ran it on my machine and it worked.
我在我的机器上运行它,并且可以正常工作。
private void BindPerson()
{
Person p2 = new Person();
p2.PersonType = "Person2";
Person p3 = new Person();
p3.PersonType = "Person3";
ListItem person2ListItem = new ListItem();
person2.Text = p2.PersonType;
person2.Value = p2.PersonType;
listBox.Items.Add(person2ListItem);
ListItem person3ListItem = new ListItem();
person3.Text = p3.PersonType;
person3.Value = p3.PersonType;
person3.Selected = true; // This will make it selected
listBox.Items.Add(person3ListItem);
}
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
BindPerson();
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.