views:

51

answers:

1

I have a simple form with list as a data source, a binding source bound to the list, and a combo box bound to the binding source with some fields editing whatever the bindingSource.Current is. What I would like to do is if a bool is set pop up a dialog asking if they want to save changes before they change items. If they say no I want to call CancelEdit() if yes I want to keep them on the current item so they can click the save button. How do I do this?

The second part of my question is because my underlining data source is a List<View> will CancelEdit() even do anything? (View is just a class with string Name and a List<CustomColumn>

Edit: Let me elaborate on what I am doing to maybe help explain what I am doing. I have a list of View, these elsewhere in the program will be enumerated to generate a DataGridView. What this menu is for is adding new "Views" and changing the order of the columns in the view (it never actually edits the the CustomColumn just adding items and changing the order of the list<CustomColumn>). What I want to happen is if someone presses cancel or changes to a new view by using the combo box without saving it will undo any changes they made to the List<CustomColumn>

+1  A: 

If I infer your question correctly, then the answer is not one that you're going to like; the ComboBox has no mechanism for cancelling a change of selection. I wish it did, as I have come across this issue time and time again. This is how i'd work around the limitation:

bool ignoreEvent = false;
object lastSelectedItem = null;

void comboBox1_SelectedIndexChanged(object sender, EventArgs e) {
    if (ignoreEvent) return;

    if (CheckForChanges()) {
        if (MessageBox.Show("Do you want to save changes?", "Save changes", MessageBoxButtons.YesNo) == DialogResult.Yes) {
            ignoreEvent = true;
            comboBox1.SelectedItem = lastSelectedItem;
            ignoreEvent = false;
        }
        else {
            // call CancelEdit() here
        }          
    }

    lastSelectedItem = comboBox1.SelectedItem;
}

Basically, the above code offers the means to revert the ComboBox to its previous selected value, without calling any event handler code in the process. Users will briefly see their item selection change, then snap back if they answer 'No' on the popup.

Also, you're correct in your assertion that CancelEdit() will essentially do nothing - the generic List collection does not support change detection. You may wish to use a DataTable or an ObservableCollection, both of which support change detection.

Bradley Smith