如何防止组合框SelectedIndexChanged触发?

时间:2013-11-26 10:52:12

标签: c# winforms combobox

我想在两个单词中返回先前的选择项而不再选择它或不触发SelectedIndexChanged方法。

这种情况:我有组合框,当选择一个项目时,datagridview会填充行。您可以在datagridview中编辑内容并将其保存到文件中。如果您不保存更改并尝试更改组合框中的项目,则会告诉您所有更改都将丢失。我创建了一个消息框,让您选择是(更改)和否(不更改)。如果单击“是”,则一切正常,但如果单击“否”,则必须返回上一个选定项。当我这样做时,我触发SelectedIndexChanged并使datagridview再次加载并删除更改。这是我在SelectedIndexChanged方法中的代码:

if (!ChangeMade)
        {
           //#1 Some Code
         }
else
        {
            DialogResult dialogResult =
            MessageBox.Show("Are you sure you want to change the manifacturer?" +
                            "\n    All the changes you have done will be lost.",
            "Warning", MessageBoxButtons.YesNo);

            if (dialogResult == DialogResult.Yes)
            {
              //same code as #1                
            }
            else
            {
               //Here must be the code that returns the previous 
               //item without selecting it.
            }

抱歉我的英文。

3 个答案:

答案 0 :(得分:3)

正如我所看到的,您只想在用户更改组合框时更改数据。对于这种情况,SelectionChangeCommitted是完美的,因为它仅在用户对combobox进行更改时触发。

private void TypeSelectionChangeCommitted(object sender, EventArgs e)
{
    if (!ChangeMade)
    {
       //#1 Some Code
    }
    else
    {
        DialogResult dialogResult =
        MessageBox.Show("Are you sure you want to change the manifacturer?" +
                        "\n    All the changes you have done will be lost.",
        "Warning", MessageBoxButtons.YesNo);

        if (dialogResult == DialogResult.Yes)
        {
          //same code as #1                
        }
        else
        {
           //Here must be the code that returns the previous 
           //item without selecting it.
        }
    }
}

有关MSDN

的更多信息

答案 1 :(得分:0)

我这样做的方式:

private void ComboBoxOnChange(...)
{
    if (!shouldTrigger)
        return;

    shouldTrigger = true;
    // Here goes your code
    should trigger = false;
}

答案 2 :(得分:-1)

  this.comboBox1.SelectedIndexChanged -= new EventHandler(comboBox1_SelectedIndexChanged);