如何在当前组合框中选择值时显示另一个组合框?

时间:2013-05-27 08:37:45

标签: c# winforms combobox windows-applications

我有一个combobox(CB1),其中包含1,2,3等项目,当我选择值combobox (CB2) visible时,我想创建另一个3 from CB1。我应该使用哪个属性。我正在开发基于Windows的应用程序,我使用C#作为语言背后的代码。一个例子就是解决问题的好方法。 组合框CBFormat包含以下项目列表:

var allWiegandFormat = WiegandConfigManager.RetrieveAllWiegandFormats();
            var allWiegandList = new List<IWiegand>(allWiegandFormat);

            CBFormat.Items.Add(allWiegandList[0].Id);
            CBFormat.Items.Add(allWiegandList[3].Id);
            CBFormat.Items.Add(allWiegandList[4].Id);
            CBFormat.Items.Add(allWiegandList[5].Id);

            CBProxCardMode.Items.Add(ProxCardMode.Three);
            CBProxCardMode.Items.Add(ProxCardMode.Five);

现在我想在CBFormat组合框中选择第二项时显示CBPorxCardMode的组合框。

4 个答案:

答案 0 :(得分:2)

试试这个

Private void CB1_SelectedIndexChanged(object sender, System.EventArgs e)
{
    Combobox CB = (ComboBox) sender;
    if(CB.SelectedIndex != -1)
    {
        int x = Convert.ToInt32(CB.Text)
        if(x == 3)
        {
          CB2.Visible = True;
        }
    }
}

答案 1 :(得分:0)

使用SelectionChangeCommitted事件并订阅您的CB1

// In form load or form initialization
cb1.SelectionChangeCommitted += ComboBoxSelectionChangeCommitted;

// Event
private void ComboBoxSelectionChangeCommitted(object sender, EventArgs e)
{
    cb2.Visible = cb1.SelectedItem != null && cb1.Text == "3";
}

答案 2 :(得分:0)

从CB2 Visible属性设置为False开始,并通过WinForms设计器为CB1上的SelectedIndexChanged添加事件处理程序代码

private void ComboBox1_SelectedIndexChanged(object sender, System.EventArgs e)
{
    ComboBox comboBox = (ComboBox) sender;
    if(comboBox.SelectedItem != null)
    {
        int id = Convert.ToInt32(comboBox.SelectedItem)
        cbo2.Visible = (id == 3)
    }
}

这假设你在第一个组合中添加的ID是一个整数值。
同样,即使您以编程方式更改SelectedItem而不仅仅是在用户更改值时,也会调用SelectedIndexChanged事件。此外,如果用户再次更改选择远离ID == 3,则该方法将再次设置Cbo2不可见。

答案 3 :(得分:0)

如果是Winforms您可以使用像这样的东西

    private void Form1_Load(object sender, EventArgs e)
    {
            comboBox1.Items.Add(1);
            comboBox1.Items.Add(2);
            comboBox1.Items.Add(3);
            comboBox2.Visible = false;
    }

    private void comboBox1_SelectedIndexChanged(object sender, EventArgs e)
    {
        if (comboBox1.SelectedItem.ToString() == "3")
        {
            comboBox2.Visible = true;
        }
        else
        {
            comboBox2.Visible = false;
        }
    }

希望这会有所帮助。