tags:

views:

4578

answers:

7

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?

A: 

You could use a message filter to intercept clicks and key presses, which would allow you to prevent the combo box's normal behaviour. But I think you'd be better off disabling the combo box when the user makes a change, and require them to either save or revert their changes.

Simon
+3  A: 

The Validating event can be used for this scenario
http://msdn.microsoft.com/en-us/library/system.windows.forms.control.validating.aspx

Aleris
This happens after you lose focus, so will not work. I need an event that happens "before" the user tries to change the value.
RG
@RG - could you not just set the focus back to the combo box, or is there some processing happening when it loses focus?
Lucas Jones
+1  A: 

You don't get an appropriate event by default. You could cache the previous value and set it back to that if the user wants to cancel.

Daniel M
A: 

Save the current value on the Enter event. Implement the BeforeValueChange logic in the ValueChanged event, before the actual ValueChanged logic. If the user cancels, set the stored value and don't continue in the method (return).

If you're going to use this system a lot, I'd suggest inheriting ComboBox and implementing your BeforeValuechange event there.

Vincent Van Den Berghe
+1  A: 

How about using the Validating / Validated events?
It works well, if the event happening on LostFocus instead of Change is ok with you.

Otherwise, how about

public void Combobox_ValueChanged(object sender, EventArgs e) {
    if (!AskUserIfHeIsSureHeWantsToChangeTheValue())
    {
        // Set previous value
        return;
    }

    // perform rest of onChange code
}
configurator
A: 

Vincent Van Den Berghe's Answer is the correct answer and is the only safe answer.

Configurator's answer is dangerous. If the combobox is bound so just by changing the value the first time other events/property changes... can happen in the form or bussiness logic, so changing it once and then changing it back can cause a lot of unwanted stuff to happen.

+1  A: 
cbx_Example.Enter += cbx_Example_Enter;
cbx_Example.SelectionChangeCommitted += cbx_Example_SelectionChangeCommitted;


...


private int prevExampleIndex = 0;
private void cbx_Example_Enter(object sender, EventArgs e)
{
    prevExampleIndex = cbx_Example.SelectedIndex;
}

private void cbx_Example_SelectionChangeCommitted(object sender, EventArgs e)
{
    // some custom flag to determine Edit mode
    if (mode == FormModes.EDIT) 
    {
        cbx_Example.SelectedIndex = prevExampleIndex;
    }
}
Sapphire
This is how I've always done it, and it works as expected.
Daniel Pryden