hen you think of using data binding in .NET it's always to structured data sources such as a DataSet, array, list etc. But in reality, you aren't limited to data residing in databases. Using data binding in Windows Forms, you can bind to almost any structure that contains data. You can bind to an array of values that you calculate at run time, that you read from a file, or that derive from the values of other controls. This article will focus on binding properties of one control to properties of another control.
In traditional data binding, you typically bind the display property (for example, the text property of a TextBox control) to your data source. With the .NET framework, you also have the option of setting other properties via binding as well. In fact, you can bind any property of any control to your data source. You might use binding for:
- Setting the graphic of an image control.
- Setting the background color of one or more controls.
- Setting the size of controls.
|Figure 1. Windows Form with Controls: The Panel on this form changes behavior based on the status of the CheckBoxes.|
In other words, data binding becomes an automatic way of setting any runtime-accessible property of any control on the form.
Figure 1 shows a Windows Form with two CheckBoxes and a Panel control. The Panel has a TextBox and a ComboBox. Selecting ChekBox1 makes the Panel visible, and selecting CheckBox2 enables the Panel. To handle this scenario you would write code to check the state of the CheckBoxes and then manipulate the Panel state appropriately. For instance:
' Code to make the panel visible
If CheckBox1.Checked = True Then
Me.Panel1.Visible = True
Me.Panel1.Visible = False
Code to enable the panel
If CheckBox2.Checked = True Then
Me.Panel1.Enabled = True
Me.Panel1.Enabled = False
The above code would have to be called during the CheckBox.CheckChanged events.
Data binding simplifies this to just two lines of code. To make it work, download the ZIP file available with this article (see the link in the left column), and open the VS.NET 2003 DataBoundUI.sln solution file and the DataBoundUI.vb form file.
|Author's Note: frmDataBoundUI.vb is the completed form that you should end up with after completing the instructions in this article.
Add the following code to the Form's load event after the comment "Add code for base binding":
Me.Panel1.DataBindings.Add("Visible", CheckBox1, "Checked")
Me.Panel1.DataBindings.Add("Enabled", CheckBox2, "Checked")
Hit F5 to run the project and try checking and unchecking the two CheckBoxes. Voila! Data binding saved you a considerable amount of time writing code.