0
votes

Currently I am setting my comboboxes datasource as such:

comboBox1.DataSource = _team;
comboBox1.DisplayMember = "Name";
comboBox1.ValueMember = "ID";

Team is a generic List of type ListItemModel which looks like:

public class ListItemModel
{
    private string _name;
    private short _id;
    public string Name
    {
        get
        {
            return this._name;
        }
    }
    public short ID
    {
        get
        {
            return this._id;
        }
    }
    public ListItemModel(string name, short id)
    {
        this._name = name;
        this._id = id;
    }
}

I am then trying to databing it as such:

comboBox1.DataBindings.Add("SelectedValue", _person.Person, "TeamId", true, DataSourceUpdateMode.OnPropertyChanged);

My datasource (model) is set up:

public class PersonViewModel : INotifyPropertyChanged
{
    public Person Person { get; set; }
    public event PropertyChangedEventHandler PropertyChanged;

    [NotifyPropertyChangedInvocator]
    protected virtual void OnPropertyChanged(PropertyChangedEventArgs e)
    {
        var handler = PropertyChanged;
        if (handler != null) handler(this, e);
    }
}

I am able to populate the combobox correctly, the OnPropertyChanged event is actually working as I can see the data changing correctly.

The issue is two fold:

1) On initial load/set up the comboboxes selectedvalue isn't set, even though I have databound it.

2) If I change the selection in the combobox and then lose focus it doesn't retain the selected value and just shows nothing selected. The OnPropertyChanged is working as I can see the TeamId changing correctly.

I am wondering what I have missed out when it comes to databinding comboboxes

1
Can you show the code of your class "Person"?DotNet Developer

1 Answers

0
votes

After spending all day on this and digging into how combo boxes bind data it ended up being a simple solution.

I ended up changing the public class ListItemModel Id property from short to int and it binds and selects the value correctly.

The databinding would fire, and set the SelectedValue property correctly, as I noted the databinding was always correct. After this the DisplayMember and ValueMember bindings would fire, checking the SelectedValue again. The ValueMember is of type short, not int, because of this it would find no match so set it to null.

Its weird how there was no exception or error and it just silently go to null.

Hopefully this is useful to anyone else coming up with this issue.