Was playing with an old application that I wrote for work and realised that I’ve completely forgotten about how data bindings work with Windows Forms applicatios. So, I thought I’d add a blog entry about it, so that I can refer back to my various pearls later.
Data binding is a nifty method of making your controls talk directly to your data. While there are other methods that may be faster, data binding is very useful for getting things up and running quickly.
All System.Windows.Forms.Control objects come with their own DataBindings member. This is the thing that allows the magic to happen.
Suppose that you had a DataTable that you were storing all of you application’s data in, and this table contained the columns customer_id, customer_name, customer_address, customer_type and so on.
To set up a databinding to these items you would use code similar to below.
// m_CustomerName is a TextBox added using the form designer
// m_DataRow is the record that you are currently editing
m_CustomerName.DataBindings.Add("Text", m_DataRow, "customer_name");
Viola, now whenever you make a change in the text box, your record will be updated as well, and as easy as adding a single line of code to your initialization function. As an added bonus, your textbox will have it’s value set to whatever is in the field when you bind it as well.
Suppose that you have a specific type that you would prefer to fill out, like the one below.
public class Customer
{
public int CustomerID {get; set;}
public String CustomerName {get; set;}
public String CustomerAddress {get; set;}
public int CustomerType {get; set;}
}
The code for doing this would be exactly the same, with the property name passed as the paramater.
m_CustomerName.DataBindings.Add("Text", m_CustomerStruct, "CustomerName");


