简体   繁体   中英

Winforms comboBox databinding whole object (no dataMember)

I've got difficulties binding a simple object to a comboBox as follow :

public partial class Planning : Form
{
    private static BindingList<VisiteVisiteur> visiteurs = new BindingList<VisiteVisiteur>(Program.model.VisiteVisiteur.ToList());
    public VisiteVisiteur visiteur = visiteurs.Last();

    public Planning()
    {
        InitializeComponent();

        comboBox1.DataSource = visiteurs;
        comboBox1.DisplayMember = "Name";
        comboBox1.DataBindings.Add("SelectedValue", visiteur, "", true, DataSourceUpdateMode.OnPropertyChanged);

I want to bind to whole visiteur object so it updates as the comboBox selectedValue changes. At the moment, the selectedValue changes but not the visiteur object. What am I doing wrong here ?

SOLUTION : Use the SelectedIndexChanged event to update the visiteur variable

public partial class Planning : Form
{
    private static BindingList<VisiteVisiteur> visiteurs = new BindingList<VisiteVisiteur>(Program.model.VisiteVisiteur.ToList());
    public VisiteVisiteur visiteur = null;

    public Planning()
    {
        InitializeComponent();

        VisiteVisiteur visiteurTemp = visiteurs.Last();

        comboBox1.SelectedIndexChanged += new System.EventHandler(comboBox1_SelectedIndexChanged);
        comboBox1.DataSource = visiteurs;
        comboBox1.DisplayMember = "Name";
        comboBox1.SelectedItem = visiteurTemp;
    }

    public void comboBox1_SelectedIndexChanged(object sender, EventArgs e)
    {
        visiteur = (VisiteVisiteur)comboBox1.SelectedItem;
    }

Answer of Crowcoder will set visiteur to comboBox1.SelectedItem only once. That is why you need to use manually updating by SelectedIndexChanged

You can do proper databinding (thanks to comment of Ivan Stoev) if you change member visiteur to a property

public VisiteVisiteur visiteur { get; set; }

Then set databinding

comboBox1.DataSource = visiteurs;
comboBox1.DisplayMember = "Name";
comboBox1.DataBindings.Add("SelectedValue", 
                           this, 
                           "visiteur", 
                           true, 
                           DataSourceUpdateMode.OnPropertyChanged);

And if you still stay with manual updating of visiteur then use SelectionChangesCommitted event instead of SelectedIndexChanged .

Using DataSource already sets the binding. You don't want to add another, you want to set the SelectedItem which is the object instance:

comboBox1.DataSource = visiteurs;
comboBox1.DisplayMember = "Name";
comboBox1.SelectedItem = visiteur;

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