I recently wanted to bind a custom class object to a text control on a form. I had to find pieces of this amongst several Google searches. So, I thought I would share how I ended up implementing it.
Suppose you have a Person class, and you want to have the person’s name show up in a textbox control on your form and stay synced if it ever changes.
Define the class as follows:
public class Person
{
string name;
public event EventHandler NameChanged;
public string Name
{
get { return name; }
set
{
name = value;
if (null != NameChanged) { NameChanged(this, EventArgs.Empty); }
}
}
}
Person _person = new Person();
In the Load event on your windows form, add this line to hook the binding up:
textBox1.DataBindings.Add(“Text”,_person,”Name”);
The DataBindings.Add hooks up the Text property of the textbox to the Name property of the _person object.
In the setter for the Name property, you must raise the event which tells the textbox that the name has changed.
MAGIC: The event must be named as your property name +”Changed”.