【问题标题】:MultiCombo Boxes that affect eachother c#相互影响的多组合框c#
【发布时间】:2018-09-19 22:36:44
【问题描述】:

假设我有三个组合框(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]);
        }
    }
}

【问题讨论】:

  • 如果您删除了多个项目,则很难在同一索引处重新添加。如果您有排序顺序,它会变得更容易。如果您不这样做,则需要存储原始订单的副本。您可以根据需要添加或插入项目。
  • 无论如何我可以将它隐藏在其他组合框中吗?
  • 不,我不这么认为。

标签: c# winforms list combobox


【解决方案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());
}

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

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

【讨论】:

    猜你喜欢
    • 2023-03-18
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-09-04
    • 2012-04-20
    • 1970-01-01
    相关资源
    最近更新 更多