PDA

View Full Version : Databinding a Single Object to Form Controls


DaveCF
05-24-2004, 06:57 PM
Hi there,

I’m having plenty of fun learning C# (thanks Microsoft) but have a question I hope somebody can answer as I’m having little luck searching the web / books.

I have a class (Person), which has several properties such as title, surname, forename, address etc. I have made this a instance variable on a form and bound the relevant controls to it using the code as follows.

txtTitle.DataBindings.Add ( new Binding("Text",objPerson,"Title") );
txtForename.DataBindings.Add ( new Binding("Text",objPerson,"Forename") );
txtSurname.DataBindings.Add ( new Binding("Text",objPerson,"Surname") );
txtDateOfBirth.DataBindings.Add ( new Binding("Text",objPerson,"DateOfBirth") );
labAge.DataBindings.Add ( new Binding("Text",objPerson,"Age") );

Please note that there is only one instance of the person object, this is not a collection.

This all works perfectly and the contents of the class are displayed accurately. When the user presses the ‘calc age’ button the objPerson.CalcAge method is called and the class calculates the persons age dependant on the date of birth, however the label labAge isn’t updated until one of the other text fields is updated. In short I need a way of refreshing the form controls to reflect the latest data in the class.

Any help is appreciated.
Cheers

DaveCF
05-26-2004, 02:44 PM
hi,

I've found the solution if anybody is interested.

I didn't add an event to the setter of each property in the person class for the databindings to use. This is done as follows.

1) in the class declare and event handler for each property that can be updated.

public event EventHandler TitleChanged;

2) in the setter raise an event if anything is binded to it.

if (TitleChanged != null)
{
TitleChanged(this, EventArgs.Empty);
}

now, as soon as you update any property, the form will be updated automatically too.

cheers
Dave.