Data binding with enums?

D

David Veeneman

I want to data bind a user control and a business object, using a
BindingSource control. The control has a 'Priority' property that takes a
'Priority' enum (High, Normal, Low). The business object has a property with
the same name, which takes an identical enum.

Data binding isn't working, and I think it's because the two enums are
different. Even though they have the same name and the same elements, they
are declared under different namespaces.

Why two enums? It lets the control and the business object be developed
independently of each other, and it reduces the coupling between them. But
apparently, it's killing the data binding between the control property and
the object property. The ability of a data binding to perform implicit
conversions does not extend this far.

Has anyone else run into a problem like this? Any suggestions? I'd like to
be able to perform a cast or a conversion as the data moves between the
control and the object, but I don't see any way to do that. Thanks in
advance.
 
D

David Veeneman

I found my answer--you simply hook into the Format and Parse events fired by
the data binding for the control property in question:

userControl1.DataBindings["Priority"].Format += new
ConvertEventHandler(EditPanelProjects_Format);
userControl1.DataBindings["Priority"].Parse += new
ConvertEventHandler(EditPanelProjects_Parse);

The event handler will take an argument of type ConvertEventArgs.

When the Format event fires, ConvertEventArgs.Value contains the raw value
from the business object. Convert it to whatever type the control needs and
set ConvertEventArgs.Value to the converted value.

When the Parse event fires, ConvertEventArgs.Value contains the formatted
value from the control. Convert it to whatever type the business object
needs and set ConvertEventArgs.Value to the converted value.

The events are designed to facilitate formatting a data value for display in
a control, and parsing a formatted value from a control for storage in a
data source. But they can be used for any type of conversion, such as the
one I need.
 
N

Nick Hounsome

Think what would happen if you changed the enums to be incompatible!
It would break your databinding however you do it.
If they can't be incompatible then they aren't independent.
Use a single enum in a separate assembly that both of your other assemblies
reference.

P.S. If you ever intend your app to be used by non english speakers then the
whole enum approach will not work because it can't be internationalized.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top