How to convert enum to a bool for DataBinding in Winforms?
.net, c#, data-binding, winforms
Solution
Winforms binding generates two important and useful events: `Format` and `Parse`.
The format event fires when pulling data from a source into a control and the Parse event fires when pulling data from a control back into the data source.
If you handle these events you can alter/retype the values going back and forth during binding.
For example here are a couple of example handlers for these events:
public static void StringValuetoEnum<T>(object sender, ConvertEventArgs cevent)
{
T type = default(T);
if (cevent.DesiredType != type.GetType()) return;
cevent.Value = Enum.Parse(type.GetType(), cevent.Value.ToString());
}
public static void EnumToStringValue<T>(object sender, ConvertEventArgs cevent)
{
//if (cevent.DesiredType != typeof(string)) return;
cevent.Value = ((int)cevent.Value).ToString();
}
And here is some code attaching these event handlers:
List<NameValuePair> bts = EnumHelper.EnumToNameValuePairList<LegalEntityType>(true, null);
this.cboIncType.DataSource = bts;
this.cboIncType.DisplayMember = "Name";
this.cboIncType.ValueMember = "Value";
Binding a = new Binding("SelectedValue", this.ActiveCustomer.Classification.BusinessType, "LegalEntityType");
a.Format += new ConvertEventHandler(ControlValueFormatter.EnumToStringValue<LegalEntityType>);
a.Parse += new ConvertEventHandler(ControlValueFormatter.StringValuetoEnum<LegalEntityType>);
this.cboIncType.DataBindings.Add(a);
So in your case you can just create a SecEnum to Bool handler for the format event and within that do something like:
SecEnum se = Enum.Parse(typeof(SecEnum), cevent.Value.ToString());
cevent.Value = (bool)(se== SecEnum.Secure);
and then reverse that during parse.
Problem
Is it possible to do this? I need to use: ``` this.ControlName.DataBindings.Add (...) ``` so I can't define logic other than bind my `enum` value to a `bool`. For example: ``` (DataClass) Data.Type (enum) ``` EDIT: I need to bind `Data.Type` which is an enum to a checkbox's `Checked` property. So if the `Data.Type` is `Secure`, I want the `SecureCheckbox` to be checked, through data binding.