I have a bunch of Checkboxes on my form with their Checked properties bound to Boolean properties on the data model:
chk1.DataBindings.Add(new BindingValue(this, "Checked", "MyBooleanProperty1", false))
chk2.DataBindings.Add(new BindingValue(this, "Checked", "MyBooleanProperty2", false))
chk3.DataBindings.Add(new BindingValue(this, "Checked", "MyBooleanProperty3", false))
There is also a shared event handler for all checkboxes on the screen that ensures the databound value is correctly set to the checked value.
private void AllCheckboxes_CheckedChanged(object sender, EventArgs e)
{
var chk = ((CheckBox)sender);
var binding = chk.DataBindings["Checked"];
if (binding != null)
binding.WriteValue();
}
In some cases, the first time this form and the bindings are loaded, I get an exception :
Cannot format the value to the desired type.
at System.ComponentModel.ReflectPropertyDescriptor.SetValue(Object component, Object value) at System.Windows.Forms.BindToObject.SetValue(Object value) at System.Windows.Forms.Binding.PullData(Boolean reformat, Boolean force) at System.Windows.Forms.Binding.WriteValue()
It works correctly for the first checkbox to process the event, but then the second one will throw this exception.
The data source is an interface of my datamodel
public interface IMyDataModel
{
bool MyBooleanProperty1 { get; set; }
bool MyBooleanProperty2 { get; set; }
bool MyBooleanProperty3 { get; set; }
}
And I can verify that the data model itself is set correctly by setting a breakpoint right before the .WriteValue in the event handler. I can even put a breakpoint in the setter of the bound boolean property, and it is also called correctly.
If I set the FormattingEnabled
property of the binding to true, it does fix the issue. But I am wondering why I even have to do that in the first place, since I am binding a System.Boolean
property in the UI object to a bool
property on the data source.
Why would I be getting this exception in this case?
IsThreeState
property? – RecountalIsThreeState
or make your binding to nullable bool. I understand this doesn't look like a null binding issue, but I expect to have null handling in checkboxes. – RecountalBindingValue
is a custom class that contains properties that is used to create the Binding in our code's infrastructure. – Hamper