Sync 2 Comboxes C#

本文关键字:Comboxes Sync | 更新日期: 2023-09-27 18:17:24

你好,我正在努力想出一个使用c#同步两个comboxes的有效方法。这两个组合框包含相同的值减去其中一个组合框中的当前选定值。

数据源= "A" "B" "C" "D"

combobx 1 current selected item = "A"combobx2当前选中的项目= "B"

需要的可用值

combobox 1 = "A" "C" "D"combobox 2 = "B" "C" "D"

实现这一点的最好方法是什么?说到编程windows窗体,我还是个新手

这是我尝试过的

是的,没有乐趣…这是我试过的

    static List<string> ds = new List<string> { "a", "b", "c", "d" };
    BindingList<string> b1 = new BindingList<string>(ds);
    BindingList<string> b2 = new BindingList<string>(ds);
    public Form1()
    {
        InitializeComponent();
        comboBox1.DataSource = b1;
        comboBox2.DataSource = b2;
    }
    private void comboBox1_SelectedIndexChanged(object sender, EventArgs e)
    {
        if (b2.Remove((string) comboBox1.SelectedItem))
        {
            b2.Remove((string) comboBox1.SelectedItem);
        }
        if (!b1.Contains((string) comboBox2.SelectedItem))
        {
            b1.Add((string) comboBox2.SelectedItem);
        }
    }
    private void comboBox2_SelectedIndexChanged(object sender, EventArgs e)
    {
        if (b1.Remove((string)comboBox2.SelectedItem))
        {
            b1.Remove((string)comboBox2.SelectedItem);
        }
        if (!b2.Contains((string)comboBox1.SelectedItem))
        {
            b2.Add((string)comboBox1.SelectedItem);
        }
    }

Sync 2 Comboxes C#

我试着用你的…

  public Form1()
    {
        InitializeComponent();
        comboBox1.DataSource = b1;
        comboBox2.DataSource = b2;
        Boolean lDoing1;
        Boolean lDoing2;
    }
   private void comboBox1_SelectedIndexChanged(object sender, EventArgs e)
    {
        if (lDoing1)
        {
         Return;
        }
        if (b2.Remove((string) comboBox1.SelectedItem))
        {
            lDoing2 = True ; 
            b2.Remove((string) comboBox1.SelectedItem);
            lDoing2 = False ;
        }
        if (!b1.Contains((string) comboBox2.SelectedItem))
        {
            b1.Add((string) comboBox2.SelectedItem);
        }
    }
    private void comboBox2_SelectedIndexChanged(object sender, EventArgs e)
    {
        if (lDoing2)
        {
         Return;
        }
        if (b1.Remove((string)comboBox2.SelectedItem))
        {
            lDoing1 = True ;
            b1.Remove((string)comboBox2.SelectedItem);
            lDoing1 = False ;
        }
        if (!b2.Contains((string)comboBox1.SelectedItem))
        {
            b2.Add((string)comboBox1.SelectedItem);
        }
    }