I searched a lot, but I didn't find the right solution.
I have a TextBox
, DataGridView
, 3 Button
s and a BindingSource
.
When I click my Button
'Change' I set the binding and data are loaded from DataGridView
to TextBox
, which works:
textBox.DataBindings.Add("text", bindingSource, "Name", true, DataSourceUpdateMode.OnPropertyChanged);
When I click now Button
'Cancel' the binding will be cleared:
textBox.DataBindings.Clear();
but the data is still transferred to the DataGridView
. I think it's because of OnPropertyChanged
. When I change it to OnValidation
, I know it will only be saved, when it's validated.
But how can I validate it or refuse validation? I have 2 Button
s, and depending on whether the 'Save' button or the 'Cancel' button is clicked, it should be transferred to DataGridView
or not.
And also with the event
textBox.Validating += textBox_Validating;
I didn't get it running, because this function is called before I can click a button.
How can I achieve this?
You can create binding with DataSourceUpdateMode.Never
and store it in a form level variable (field). Then you can use WriteValue
method to apply the changes (respectively ReadValue
to revert the changes).
Something like this:
form:
Binding nameBinding;
Change button click:
nameBinding = textBox.DataBindings.Add("Text", bindingSource, "Name", true, DataSourceUpdateMode.Never);
Cancel button click:
nameBinding.ReadValue();
textBox.DataBindings.Clear();
nameBinding = null;
Save button click:
nameBinding.WriteValue();
textBox.DataBindings.Clear();
nameBinding = null;