如何遍历具有启用禁用状态的三个与选择相关的组合框

本文关键字:三个 选择 组合 遍历 何遍历 启用 状态 | 更新日期: 2023-09-27 18:02:52

我花了很多时间试图解决这个问题。我有3个组合框,我试图使第一次活动时,表单加载和其余的不活动。当值(双类型)在第一个cmb中被选中时,第二个cmb被激活,第一个cmb变为非活动状态,然后第二个cmb被选中,第一个cmb保持非活动状态,第二个cmb变为非活动状态,在从第三个组合框中选择值后,激活第三个cmb,首先激活,其余的激活,直到选择再次开始。

这是在WINDOWS窗体

我尝试过循环,但很快就变得非常复杂:-(我希望这足够清楚:-)

谢谢

如何遍历具有启用禁用状态的三个与选择相关的组合框

我将为组合框创建一个数组,并让所有3个组合框使用相同的SelectedIndexChanged处理程序:

// List the combo boxes in the order you want them to enable.
ComboBox[] _boxes = { comboBox1, comboBox2, comboBox3 };
private void ComboBox_SelectedIndexChanged(object sender, EventArgs e)
{
    int index = Array.IndexOf(_boxes, (ComboBox)sender);
    // Disable the combo box that just got its value selected.
    _boxes[index].Enabled = false;
    // If it's not the last combo box in the array, enable the next one.
    if(index < _boxes.Length - 1)
        _boxes[index + 1].Enabled = true;
}

然后你只需要设置组合框的初始状态,使第一个是启用的,其他两个是不启用的。

这也很容易扩展。如果您决定在流中添加另一个组合框,则只需将其添加到_boxes数组中。

您需要使用事件,如selectionchangecomcommitted。事件处理程序用于在满足某些条件时自动调用方法,因此允许您执行某些条件操作,而无需循环轮询。下面是一个示例,它应该可以满足您的要求,尽管它可能会导致一个不太友好的用户界面。

public partial class ExampleForm : Form
{
    public ExampleForm()
    {
        InitializeComponent();
        comboBox1.Enabled = true;
        comboBox2.Enabled = false;
        comboBox3.Enabled = false;
        comboBox1.Items.Add("option1");
        comboBox1.Items.Add("option2");
        comboBox2.Items.Add("option1");
        comboBox2.Items.Add("option2");
        comboBox3.Items.Add("option1");
        comboBox3.Items.Add("option2");
        comboBox1.OnSelectedIndexChanged += comboBox1_OnSelectedIndexChanged;
        comboBox2.OnSelectedIndexChanged += comboBox2_OnSelectedIndexChanged;
        comboBox3.OnSelectedIndexChanged += comboBox3_OnSelectedIndexChanged;
    }
    void comboBox1_OnSelectedIndexChanged(object sender, EventArgs e)
    {
        comboBox1.Enabled = false;
        comboBox2.Enabled = true;
    }
    void comboBox2_OnSelectedIndexChanged(object sender, EventArgs e)
    {
        comboBox2.Enabled = false;
        comboBox3.Enabled = true;
    }
    void comboBox3_OnSelectedIndexChanged(object sender, EventArgs e)
    {
        comboBox1.Enabled = true;
        comboBox3.Enabled = false;
    }
}