17 November 2006

Windows Forms data binding and notification of changed properties

Yesterday a college of mine asked me a question: "How to refresh TextBox control in Windows forms application binded to a property of object, when the property change its value?". The solution is very simple, but according to me not very well documented (at least in books I read).


Solution: Provide event named PropertyNameChanged, where PropertyName is the name of property binded to the TextBox. During the binding process, the text box inspects binded object for event with the mentioned signature and binds to it. The sample code looks like this:


public class Customer
{
    private string mName;
 
    public string Name
    {
        get { return mName; }
        set
        {
            mName = value;
            if (NameChanged != null)
            {
                NameChanged(this, EventArgs.Empty);
            }
        }
    }
 
    public event EventHandler NameChanged;
}
 
Customer cust = new Customer();
textBox1.DataBindings.Add("Text", cust, "Name");
 
Another possible solution is to remove and add binding of the text box to the object. You can write general routine to loop through each control for a given form and remove-add binding. This is nasty solution of course.