Alex Rivera | Logout

How to prevent/cancel a combobox's value change in c#?

Asked 2008-11-24T15:36:34.000
25

I have a combobox at the top of a form that loads editable data into fields below. If the user has made changes, but not saved, and tries to select a different option from the combobox, I want to warn them and give them a chance to cancel or save.

I am in need of a "BeforeValueChange" event with a cancelable event argument.

Any advice on how to accomplish?

Edit
Report

1 Answer

8

Here is the simplest fix:-

        bool isSelectionHandled = true;

        void CmbBx_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            if (isSelectionHandled)
            {
                MessageBoxResult result = MessageBox.Show("Do you wish to continue selection change?", this.Title, MessageBoxButton.YesNo, MessageBoxImage.Question);
                if (result == MessageBoxResult.No)
                {
                    ComboBox combo = (ComboBox)sender;
                    isSelectionHandled = false;
                    if (e.RemovedItems.Count > 0)
                        combo.SelectedItem = e.RemovedItems[0];
                    return;
                }
            }
            isSelectionHandled = true;
        }
answered 2011-04-20T15:58:03.280

Your Answer