I just ran into an interesting issue related to data binding. I have a custom control in a windows forms application that manages the app's configuration. I also have a configuration object. The control is the view for the configuration object.
I had bound the object properties to controls using the following idiom
private void bind() { SeeRectangle.DataBindings.Add("Checked", configuration, "ShowAnswer"); // Checkbox OrderingTypeSelection.DataBindings.Add("SelectedItem", configuration, "OrderingMode"); // ComboBox AnswerPath.DataBindings.Add("Text", configuration, "AnswerPath"); // TextBox }
When adding a data biding via the Add() method of the DataBinding specialized collection, the arguments are the property of the control that will be bound, followed by the object that we will bind with, followed by the property of the object that is binding. The checkbox and combobox worked fine. I wasn't getting expected results with the textbox binding.
I had tried to assign the value of the Text property of the textbox with the following code
var openDirectory = new FolderBrowserDialog(); var answer = openDirectory.ShowDialog(); if (answer == DialogResult.OK) { if (configuration != null) { AnswerPath.Text = openDirectory.SelectedPath; } }
And the textbox was correctly assigned. However, the binding with the configuration object kept failing. What I discovered was that there must be an event that is not triggered when assigning values via code. If I changed the values in the textbox, the assignment would happen.
So the workaround was to explicitly assign the value from the FolderBroswerDialog to the configuration object.
var openDirectory = new FolderBrowserDialog(); var answer = openDirectory.ShowDialog(); if (answer == DialogResult.OK) { if (configuration != null) { AnswerPath.Text = openDirectory.SelectedPath; configuration.AnswerPath = openDirectory.SelectedPath; // <--- the solution } }