【问题标题】:How to prevent combobox SelectedIndexChanged to trigger?如何防止组合框 SelectedIndexChanged 触发?
【发布时间】:2013-11-26 10:52:11
【问题描述】:

简而言之,我想返回上一个选定项而不再次选择它或不触发 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.
            }

对不起我的英语。

【问题讨论】:

    标签: c# winforms combobox


    【解决方案1】:

    正如我所见,您只想在用户更改组合框时更改数据。对于这种情况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

    【讨论】:

    • 这显然是一个更好的解决方案。很高兴学到一些东西。谢谢!
    • 感谢您的回答。我试试你和 Dethariel 的答案。他们都在工作,但我认为你的更好。
    【解决方案2】:

    我这样做的方式:

    private void ComboBoxOnChange(...)
    {
        if (!shouldTrigger)
            return;
    
        shouldTrigger = true;
        // Here goes your code
        should trigger = false;
    }
    

    【讨论】:

      【解决方案3】:
        this.comboBox1.SelectedIndexChanged -= new EventHandler(comboBox1_SelectedIndexChanged);
      

      【讨论】:

        猜你喜欢
        • 2011-03-16
        • 2011-11-28
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2012-11-06
        • 1970-01-01
        相关资源
        最近更新 更多