影响彼此c#的MultiCombo Box

时间:2018-04-10 10:34:19

标签: c# winforms list combobox

所以说我有三个组合框(cmb1,cmb2,cmb3),每个组合中有三个项目(a,b,c)。如果我选择cmb1中的项目说" a"然后我使用cmb2或cmb3它只剩下b和c,如果我取消选择a那么它将被重新添加回列表中。 如何成功删除并重新添加?

List<string> list = new List<string>();
    private void Form1_Load(object sender, EventArgs e)
    {
        list.Add("a");
        list.Add("b");
        list.Add("c");

        foreach (string i in list)
        {
            comboBox1.Items.Add(i);
            comboBox2.Items.Add(i);
            comboBox3.Items.Add(i);
        }//adds list items to combo boxes
    }

    private void comboBox1_TextChanged(object sender, EventArgs e)
    {
        if(comboBox1.Text == list[0].ToString())
        {
            comboBox2.Items.Remove(list[0]);
            comboBox3.Items.Remove(list[0]);
        }// removes item from other lists if chosen from one

        if (comboBox1.Text == list[1].ToString())
        {
            comboBox2.Items.Remove(list[1]);
            comboBox3.Items.Remove(list[1]);
        }

        if (comboBox1.Text == list[2].ToString())
        {
            comboBox2.Items.Remove(list[2]);
            comboBox3.Items.Remove(list[2]);
        }
    }
}

1 个答案:

答案 0 :(得分:1)

这可以简化:

List<string> list = new List<string>();
private void Form1_Load(object sender, EventArgs e)
{
    list.AddRange(new string[] { "a", "b", "c" });

    comboBox1.Items.AddRange(list.ToArray());
    comboBox2.Items.AddRange(list.ToArray());
    comboBox3.Items.AddRange(list.ToArray());
}

使用comboBox1 SelectionChangeCommitted事件和一个字段来存储选择项目,添加和删除其他组合框中的项目:

private int PreviousSelectedIndex = -1;

private void comboBox1_SelectionChangeCommitted(object sender, EventArgs e)
{
    if (comboBox1.SelectedIndex < 0) return;
    if (PreviousSelectedIndex > -1)
    {
        comboBox2.Items.Insert(PreviousSelectedIndex, comboBox1.Items[PreviousSelectedIndex]);
        comboBox3.Items.Insert(PreviousSelectedIndex, comboBox1.Items[PreviousSelectedIndex]);
    }

    comboBox2.Items.RemoveAt(comboBox1.SelectedIndex);
    comboBox3.Items.RemoveAt(comboBox1.SelectedIndex);
    PreviousSelectedIndex = comboBox1.SelectedIndex;
}