簡體   English   中英

當我更改combobox1時,它也會同時更改combobox2中的值(都使用相同的List)

[英]when I change combobox1 it also changes the values in combobox2 (both use the same List)

我的Winform上有2個組合框。 這兩個組合框均由下面的列表加載。 一切正常。 例外,當我更改Combobox1中的值時,它也會更改combobox2中的值...其他組合框也是如此。 當我更改組合框2中的值時,它也會更改組合框1中的值。

兩者都必須使用相同的值列表。 所以這就是為什么我只綁定到同一列表(_item)的原因。

所以我需要怎么做才能使兩個組合框彼此分離?

   IList<CompteGeneral> _item = new List<CompteGeneral>(compt_repository.GetAll);
            combobox1.DataSource = _item;
            combobox1.DisplayMember = "AccountNumber";

            combobox2.DataSource = _item;
            combobox2.DisplayMember = "AccountNumber";
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";

要么

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";

通過在構造函數中傳遞_item1來創建具有相同項目的新List。

將新列表分配給第二個組合框。

        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";

CompteGeneral ICloneable接口實現Clone方法

  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";

克隆對象時,還要搜索ShallowCopy和DeepCopy范例。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM