简体   繁体   中英

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.

I then have an object, for example called Person. This object will contain a property called PersonType, which maybe 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. 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();
        }
    }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM