Shaun
Shaun

Reputation: 245

How to get databounded ComboBox to reflect changes made to a BindingList datasource

I have a class that has a String for a name and a int for an ID number:

public class Item
{
    public int IDNumber { get; set; }
    public String Name  { get; set; }
}

I have a List<Item> of them that I used to create a BindingList<Item>. The BindingList<Item> is the DataSource for a ComboBox which I have databounded. I have the Display Member currently as the Name and Value Member currently as IDNumber.

I can change the Name but when I do the value of ComboBox.SelectedText becomes "". To be more clear say that the Name is "Dave". The user inputs "John". I want the SelectedText to change to "John" but it instead becomes "".

I have tried using INotifyPropertyChanged:

public class Item : INotifyPropertyChanged
{
    private String name;

    public int IDNumber { get; set; }
    public String Name
    {
        get
        {
            return name;
        }
        set
        {
            this.name = value;
            if (this.PropertyChanged != null)
            {
                this.PropertyChanged(this, new PropertyChangedEventArgs("Name"));
            }
        }

        public event PropertyChangedEventHandler PropertyChanged;
    }
}

This will do the trick only after clicking the ComboBox once before using the SelectedText field whereas I want it to be updated when the change is made.

Does anyone know how I can get around this?

Thanks.

Upvotes: 2

Views: 3572

Answers (2)

Micah Armantrout
Micah Armantrout

Reputation: 6971

Use a Binding Source

Call Reset Bindings

Example:

private BindingSource bs;

private SetupBinding()
{
    List<Item> data = new List<Item>();


    //Get Data 



    bs = new bindingsource();
    bs.datasource = data;
    combobox.datasource = bs;
    comboBox.DisplayMember="Name";
    comboBox.ValueMember="IDNumber";
}

private ShowMyMessage()
{
    MessageBox.Show(this, message, caption, buttons,
            MessageBoxIcon.Question, MessageBoxDefaultButton.Button1, 
            MessageBoxOptions.RightAlign);
 if (bs != null)
 {
   bs.resetbindings(false);
 }
}  

Then make sure your combobox has something selected and try selectedtext

Upvotes: 2

Obama
Obama

Reputation: 2612

Use comboBox.SelectedValue

so you have to set its DisplayMember and ValueMember

like

comboBox.DisplayMember="Name";
comboBox.ValueMember="IDNumber";

and finally set your datasource

Upvotes: 1

Related Questions