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; }
            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.


Galcho[MCSD.NET] said...

Nice touch.
I wrote an article how to discard changes in business objects made using data bindings.

I will glad to hear your comments :)


Stephan Zahariev said...

Your article is excellent as one of the comments in codeproject says. I will recommend it to all of my friends.
Discarding changes in business objects is major issue in every winforms application. During the years I have seen a lot of complex and nasty resolutions, but your approach is simple and yet powerful. I always appreciate solutions like this.

Stefan said...

I think INotifyPropertyChanged can also do the work.

Stephan Zahariev said...

Thanks Namesake.
I have missed INotifyPropertyChanged interface.