同步2个Comboxes C#

时间:2013-06-08 08:43:42

标签: c# combobox datasource sync

嗨,我正在努力想出一个有效的方法来同步2个没有c#的combox。 2个COMbox包含相同的值减去组合框中当前选定的值。

即。

Datasource =“A”“B”“C”“D”

combobx 1当前所选项目=“A” combobx 2当前选择的项目=“B”

需要的可用值

组合框1 =“A”“C”“D” 组合框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);
        }
    }

1 个答案:

答案 0 :(得分:0)

我和你一起试试..

  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);
        }
    }