• Databinding with Windows Forms controls

    by  • December 8, 2008 • .net, c#, databinding, winforms • 0 Comments

    In years gone by, to add a collection of items to a collection control, I’ve gone through the long winded way of calling Items.Add on a control, such as a ComboBox. The problem is it is then difficult to resolve the reference of the item you have selected, plus extra code is necessary to clear the items and re-add them when the collection to which the ComboBox is a representation of, changes.

    I then leapt into the world of ASP.NET development where most WebForm controls can be bound to a data source really easily, mostly through a) setting the control’s DataSource property and b) a call to DataBind() on the control, and then asked the question whether it the same can be done in WinForms.

    It seems it can be, though only on a limited number of controls. This example shows me databinding to a ComboBox but I’m sure this can be used on other collection oriented controls.

    In my Form’s constructor I set up all the data sources, e.g:

    myComboBox.DataSource = myCollection //myCollection is a List

    This is sufficient to bind the collection to the control, but only does a one time data binding. Therefore the binding is not updated if myCollection is updated.

    In order to update the binding on a change to myCollection, I created a helper method called Rebind:

    public static void Rebind(BindingContext ctx, object toRebind)
           {
               ctx[toRebind].SuspendBinding();
               ctx[toRebind].ResumeBinding();
           }

    The first argument I provide is the BindingContext, which is the BindingContext property of the parent form hosting the myComboBox control. The second argument is the object you have databound the control to. In this case,

    Util.Rebind(this.BindingContext, myCollection);   //this = instance of form

     

    This is really handy as now, the SelectedItem property of myComboBox corresponds to the object reference of the item, which you can cast to be of the appropriate type.The only thing remaining is to make the string representation of the item being bound meaningful, rather than the name of the class. I modified this representation by overriding the toString() method on the class to be something a little more appropriate.

    About

    .NET developer at thetrainline.com, previously web developer at MRM Meteorite. Awarded a PhD in misbehaviour detection in wireless ad-hoc networks.A keen C# ASP.net developer bridging the gap with APIs and JavaScript frameworks, one web app at a time.

    http://www.paulkiddie.com

    Leave a Reply

    Your email address will not be published. Required fields are marked *