In one of the projects I'm on we're doing lots and lots of Winforms data binding. One of the forms is composed of 12 different tabs each with about 2 dozen controls and grids and what not (don't kill the messenger! that's what porting an old system looks like...) all needing to be bound to multiple datasets and data views.*shudder*
I can tell you this much - with this much controls on one form - your code and especially binding code is gonna get really ugly real fast. especially tedious . Oh, its nothing too hard - just lots of the same work done on a different target and source every time.
one of the things we've come up with to ease our pain is a simple Custom attribute that you can put on a control instance on the form (TextBox for example) that has some meta-data as to what data binding it will use at run time.
since this is not the simple lovable drag and drop binding GUI demos you see at conferences, you only really have the data you want at runtime and no way to do binding at design time - this is a very simple way to make a lot of that tedious code disappear. Here's how it looks on our form:
public class Form1 : System.Windows.Forms.Form { [BindToField("Products.ProductName")] public System.Windows.Forms.TextBox txtName;
[BindToValueList("Categories.CategoryName","CategoryID")] public System.Windows.Forms.ComboBox cmbCategories;
What we actually do at run time is do a very simple call to a bind helper class:
public Form1() {
InitializeComponent(); new SimpleDataComponent().FillNorthwindData(m_dataset);
//this is the simple way ControlBinder.BindControls(this,m_dataset);
The binder will automatically seek out all the controls with the custom attribute on them and bind them automatically to the appropriate data source. for controls that display lists of values (appropriately derived from ListControl) we have a "BindToValueListAttribute" for that purpose.
The nice thing is that the attribute and binder object have the ability to let you specify more advanced properties for binding. for example (none of these are shown in this post)-
you can specific to exactly what property on the control your data source will be bound to.
you can put multiple attributes on a control to add multiple data bindings to it.
you can add a category to an attribute and have the binder bind only to controls that posses this property. this allows you to have multiple data sources (which can be multiple data views for example) on one form, each bound to a different set of controls on the form, differentiate by category names on the attributes of the controls.
This is a great exercise in using Reflection - which I have to say I'm falling for more and more each time I use it. So elegant and simple. I love it. Feel free to add comments and or requests and or bugs on this post.