限制用户在Combobox c#winform中选择上一个索引的值

时间:2017-10-23 18:10:53

标签: c# winforms enums combobox

我在winform中有一个Combobox。它与枚举结合在一起。枚举显示订单中商品的状态。我希望用户按照订单操作并限制用户在更新时选择以前的状态。我尝试过selectedIndexchanged事件,但它没有用。

public enum Articlestatus : Byte
    {
        Inplagiarism = 0,
        Consentletter = 1,
        Inreview = 2,
        AuthorRevision = 4,
        ReReview = 8,
        Reject = 16,
        Accept = 32,
        Published = 64
    }

1 个答案:

答案 0 :(得分:0)

一种方法是跟踪变量中先前选择的项目,然后在SelectedIndexChanged事件中,如果用户尝试选择较少的项目,则重新选择前一项目:

// Keep track of currently selected index
private int lastSelectedIndex = 0;

private void Form1_Load(object sender, EventArgs e)
{
    comboBox1.DataSource = Enum.GetValues(typeof(Articlestatus));
    comboBox1.DropDownStyle = ComboBoxStyle.DropDownList;

    // Select first item and update our tracking variable
    comboBox1.SelectedIndex = 0;
    lastSelectedIndex = comboBox1.SelectedIndex;
}

private void comboBox1_SelectedIndexChanged(object sender, EventArgs e)
{
    // Do nothing if they re-selected the same item
    if (comboBox1.SelectedIndex == lastSelectedIndex) return;

    // If the newly selected item is less than the previous one, reset to previous one
    if (comboBox1.SelectedIndex < lastSelectedIndex)
    {
        comboBox1.SelectedIndex = lastSelectedIndex;
    }
    else
    {
        lastSelectedIndex = comboBox1.SelectedIndex;
    }
}

请注意,此代码对用户来说不是非常灵活。如果他们不小心选择了错误的物品,他们就会卡住。我想更新lastSelectedIndex的代码应该放在其他地方,就像在某些&#34; TaskCompleted&#34;事件,当被解雇时,表示他们已经做了一些事情,让他们参与选择。