Friday, November 11, 2005

Using Data Binding to Synchronize Properties

Windows forms controls have a DataBindings collection that contains the defined data bindings for the control. This is most often used to bind controls to a data source but it can be used for other purposes as well. For example, suppose your form contains a number of controls that have the same background color. When the color of one changes, the color of the other should change as well. By defining a binding between the controls' BackColor properties, this will happen automatically, making it unnecessary to write code that changes each control individually. Change one and all the others follow suit.

The following code, for example, binds the BackColor property of TextBox2 and TextBox3 to the same property of TextBox1:

Me.TextBox2.DataBindings.Add("BackColor", Me.TextBox1, "BackColor")Me.TextBox3.DataBindings.Add("BackColor", Me.TextBox1, "BackColor")

When you want to change the BackColor of all three textboxes, all you need to do is change the property for TextBox1:

Me.TextBox1.BackColor = Color.Red

By using data bindings you can achieve all sorts of useful synchronization effects. This tip is from paitken

No comments: