Home > View Post

DataBinding made simple

NEWSFLASH: WinForms Databinding is not difficult!

A lot of people are scared by databinding in WinForms and I can well understand why. Often, you're just throwing together a simple application and the learning curve seems too steep when you can just stick to wiring up objects to your controls manually (and then write some parsing code etc).

The truth, however, is that the Windows Forms declarative DataBinding model (in .NET 2.0) is beautifully simple and even the simplest of your apps should take advantage. In this post, we'll get you up and running in 10 minutes and even throw in some 'Advanced' stuff for free.

A simple form

Lets start off with a nice simple form:

Employee form

.. and an appropriate class:

class Employee
{
    private string _firstName;
    public string FirstName
    {
        get { return _firstName; }
        set { _firstName = value; }
    }

    private string _surname;
    public string Surname
    {
        get { return _surname; }
        set { _surname = value; }
    }

    private decimal _salary;
    public decimal Salary
    {
        get { return _salary; }
        set { _salary = value; }
    }
}

Add a Data Source

Next we need to make our Employee class a DataSource. Simply click Data -> Add New Data Source... in your project. Choose Object then Next. Navigate to your Employee class and press OK.

Add data source

We're almost ready to start databinding. Click Data -> Show Data Sources:

Show Data Sources

Then, by expanding the Employee node, you can drag the FirstName field onto the First Name TextBox. Two things will now happen, by magic:
  1. A BindingSource will be added to your form (called employeeBindingSource in this example)
  2. The FirstName property of an Employee will be bound to the Text property of the FirstName TextBox
And that's pretty much it. Now for the science bit.

Advanced DataBinding

We're going to use some of the 'Advanced' features for our final two textboxes. Select the appropriate control and expand the DataBindings element in the Properties window.

DataBindings

You can now manually wire up your data source and the appropriate property to the text property of your control.

Once you've done this for both the Surname and Salary boxes, choose the Advanced property (under the DataBinding property, just click the ellipsis button) for the Salary TextBox. This will display the Formatting and Advanced Binding dialog. Here we're going to use one of my favourite databinding features: formatting. To format the Salary textbox to display its value as a Currency simply choose Currency as the Format Type. What could be easier.

Advanced DataBindings

Finally

The only thing you need to do now is to associate some data with your BindingSource. Typically, this happens when your view (the form) is passed some data. But you could equally do this in your load event as shown below, or whereever appropriate for your application.

private Employee _employee;

public void Form1_Load(object sender, EventArgs e)
{
    // for the purposes of the example, lets
    // make up an employee in the load.
    _employee = new Employee();
    _employee.FirstName = "Mickey";
    _employee.Surname = "Mouse";
    _employee.Salary = 300000;

    BindEmployee();
}

public void BindEmployee()
{
    // this is where the magic happens.
    employeeBindingSource = _employee;
}

Form with databinding

Notice that the Salary TextBox is actually formatted as "$300,000.00". Sweet!

Also, try and enter some nonsense into the salary box, like "aasdf" and you'll find the DataBinding engine won't let you because the underlying type is a decimal. Tidy!

Finally, any valid changes you make to the form controls are passed back to the _employee object, so when you need to save changes...

private void btnOk_Click(object sender, EventArgs e)
{
    // joke code, but you get the idea.
    MyService.UpdateEmployee(_employee);
}

You can also download the source from the example if you like. We'll hopefully post about some more databinding related topics shortly, including INotifyPropertyChanged and ErrorProviders.

Download the source

In the meantime, Why not check out my other databinding posts: DataBinding and Nullable types and DataBinding on SelectedIndexChanged.

Tags: WinForms.NET

 
Bruusi Post By Bruusi
9:39 AM
01 Nov 2006

» Next Post: NullableExtender revisited
« Previous Post: The Awesome Power of IoC Part III

Comments are closed for this post.

© 2005 - 2017 Josh Twist - All Rights Reserved.