Georgi
Georgi

Reputation: 529

How to prevent combobox SelectedIndexChanged to trigger?

In two words I want to return the previous selecteditem without selecting it again or without triggering the SelectedIndexChanged method.

This is the situation: I have combo box and when a item is selected, datagridview is filled with rows. You can edit things in the datagridview and save them to a file. If you don't save the changes and try to change the item in the combo box it tells you that all the changes will be lost. I make a messagebox that make you choose between yes(to change) and no(not to change). If you click yes everything is OK, but if you click NO then I have to return the previous selected item. When I do so I trigger SelectedIndexChanged and that makes the datagridview load again and delete the changes. Here is my code in the SelectedIndexChanged method:

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.
            }

Sorry for my english.

Upvotes: 1

Views: 1532

Answers (3)

Dethariel
Dethariel

Reputation: 3624

The way I do this:

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

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

Upvotes: 0

gzaxx
gzaxx

Reputation: 17600

As I see it you want to change data only when user changes combo box. For this scenario SelectionChangeCommitted is perfect because it only triggers when user makes changes to 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.
        }
    }
}

More info on MSDN

Upvotes: 4

Monika
Monika

Reputation: 2210

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

Upvotes: -1

Related Questions