Alex
Alex

Reputation: 828

C# Combo box events

Currently I'm in the middle of making a small app in c# that requires the user to make a selection of an object using a combo box, from there the user can edit properties of that object below and then save them to a database.

I'm having an issue though when trying to ask the user whether they would like to cancel when they click on the combo box again but have changes to save.

the best I have is below, but users can still use a keyboard to select items even when the drop down height means they can't see the options.

private void cmbBooks_DropDown( object sender, EventArgs e )
        {
        if ( CheckSave( ) )     //checksave returns true if they want to cancel
            {
            cmbBooks.DropDownHeight = 1;
            }
        }

thanks

EDIT I've tried it with the SelectedIndexChanged event and from there I can stop the box carrying on and opening that object but then the combo box would stay selecting the object they tried to select and the combo box still stays open?

Upvotes: 1

Views: 5121

Answers (1)

Nikhil Agrawal
Nikhil Agrawal

Reputation: 48568

Check for SelectedIndexChanged event. There set the SelectedIndex Property back to earlier value if user cancels.

For your comment

Create a global bool flag with value false. Check for this value inside SelectedIndexChanged event.

If it is true. 
    return from code
Else 
    continue with your code. 

Now when you set previous selected index property set this flag to true. It will fire SelectedIndexChanged event but this time since flag is true, so it will return from the event.

In Next Line set flag = false. If you do not set it again to false, it will return out of code always.

bool flag = false;
private void mycombobox_SelectionIndexChanged(object sender, EventArgs e)
{
  If (flag)
    return;

  //Your normal code.

  If (Canceledbyuser == true)
  {
      flag = true;
      mucomboBox.SelectedIndex = previousindex;
      flag = false;
  }
}

Upvotes: 1

Related Questions