Reputation: 2908
I've 2 combobox on my winform. Both comboboxes are loaded by the list below. Everything works fine. Except, when I change a value in Combobox1 then it also changes the value in combobox2... and the same for other combobox. When I change a value in combobox 2 it changes in combobox1....
Both have to use the same list of values. so that's the reason why I just bind to the same list (_item).
so what do I need to do to decouple the 2 comboboxes from each other?
IList<CompteGeneral> _item = new List<CompteGeneral>(compt_repository.GetAll);
combobox1.DataSource = _item;
combobox1.DisplayMember = "AccountNumber";
combobox2.DataSource = _item;
combobox2.DisplayMember = "AccountNumber";
Upvotes: 0
Views: 324
Reputation: 2666
implement the Clone method from ICloneable
interface on CompteGeneral
IList<CompteGeneral> _item = new List<CompteGeneral>(compt_repository.GetAll);
combobox1.DataSource = _item;
combobox1.DisplayMember = "AccountNumber";
combobox2.DataSource = _item.Select(p => p.Clone()).ToList();
combobox2.DisplayMember = "AccountNumber";
Also search for ShallowCopy and DeepCopy paradigms when cloning objects.
Upvotes: 1
Reputation: 2597
Create a new List with the same item by passing the _item1
in the constructor.
Assign the new list to the second Combobox.
IList<CompteGeneral> _item1 = new List<CompteGeneral>(compt_repository.GetAll);
IList<CompteGeneral> _item2 = new List<CompteGeneral>(_item1);
combobox1.DataSource = _item1;
combobox1.DisplayMember = "AccountNumber";
combobox2.DataSource = _item2;
combobox2.DisplayMember = "AccountNumber";
Upvotes: 1
Reputation: 346
IList<CompteGeneral> _item = new List<CompteGeneral>(compt_repository.GetAll);
IList<CompteGeneral> _item1 = new List<CompteGeneral>(compt_repository.GetAll);
combobox1.DataSource = _item;
combobox1.DisplayMember = "AccountNumber";
combobox2.DataSource = _item1;
combobox2.DisplayMember = "AccountNumber";
or
IList<CompteGeneral> _item = new List<CompteGeneral>(compt_repository.GetAll);
BindingSource source=new BindingSource();
source.DataSource=_item ;
BindingSource source1=new BindingSource();
source1.DataSource=_item ;
combobox1.DataSource = source;
combobox1.DisplayMember = "AccountNumber";
combobox2.DataSource = source1;
combobox2.DisplayMember = "AccountNumber";
Upvotes: 1