Binding Custom Objects to Forms

Yesterday I read an msdn article that describes a method of using reflection to bind objects to a web form. It’s mirrors a technique I’ve been using for almost a year now:

  • Create a UserControl base class with a ‘BoundEntity’ property, which is the entity or object that is to be bound to the control.
  • Specify two methods; BindEntityToControl, and BindControlToEntity. The first takes the BoundEntity and populates corresponding server control properties based on the public Properties of the BoundEntity. The second does the reverse… Populating the BoundEntity properties from their corresponding server controls.
  • Use reflection to find controls that correspond to BoundEntity properties, and then set them accordingly. Controls are mapped to properties by a simple naming convention; control ID’s must have the same value as a BoundEntity property name to be bound.

The main difference in the implementation is that I do the binding with UserControls, while the article uses web forms. I think it makes more sense with my UserControl approach, because it lends itself more to an MVC approach. You can then use the codebehind files as simple Page Controllers, with the UserControl as the view, and the BoundEntity as the model.

Here’s an example of the EntityControl base class I’ve been using: