views:

40

answers:

2

How can I implement a form with simple components (text boxes, comboboxes) bound to an object's properties and have Save/Cancel support?

I have tried the code snippet at http://fgheysels.blogspot.com/2009/06/winforms-databinding-on-cancellable.html but I dont know what is required for this to work binding to object properties.

This is what I have but I cant figure out how to get the cancel button to prevent the objects property from being updated. The properties are updated with whatever value was last input, even when the cancel button was pressed.

    public DocumentProperties(FileFormatReader fileReader)
    {
        binding = new BindingSource();
        binding.DataSource = fileReader.Header;
        bindingManager = BindingContext[binding.DataSource];

        unitComboBox.DataSource = Enum.GetNames(typeof(Constants.Units));
        unitComboBox.DataBindings.Add("SelectedIndex", binding.DataSource, "UnitNumberIndex");

        operatorTextBox.Text = fileReader.Header.OperatorName;
        operatorTextBox.DataBindings.Add("Text", binding, "OperatorName");

        binding.SuspendBinding();       // Doesnt work
   }

    private void okButton_Click(object sender, EventArgs e)
    {
        binding.ResumeBinding();
        this.DialogResult = DialogResult.OK;
    }

    private void cancelButton_Click(object sender, EventArgs e)
    {
        this.DialogResult = DialogResult.Cancel;
    }

Any suggestions on how to do this would be appreciated.

+1  A: 

Cache the value when you open it, and reset it to the cached value in the cancel buttons handler.

Jimmy Hoffa
+1  A: 

The object you are binding should implement IEditableObject Interface which has methods for beginning, ending and canceling editing.

Giorgi
Thanks. I tried using this but for some reason the BeginEdit() was firing three times and the EndEdit() was also firing during the form load. Really weird.
Mark Stahler