As stated here, you use object binding in a WinForms application by following these steps:
1. Build the business objects for your application.
2. Define a business object data source in the Windows Application
project containing your user interface.
3. Bind properties of the controls on the form to business object
properties.
The first two steps were detailed here. This post covers the third step.
NOTE: You will not be able to follow along with the information in this post unless you perform steps 1 and 2 first from my prior post.
Binding to Existing Controls
Once you have at least one data source set up in your Data Sources window, you can bind it to your user interface. The technique you use to set up the binding is slightly different, depending on whether you are working with existing controls or creating new controls. This section describes the former, and the next section details the latter.
The process of binding existing controls on a form to a data source is
referred to as connect-the-dots binding. It is as easy as connecting point
A to point B.
To bind an existing control to a business object property displayed in
the Data Sources window:
1. Open the form you want to bind in the Forms Designer.
2. Open the Data Sources window. Position the Data Sources window so that you can easily see its contents and the Forms Designer at the same time.
3. Drag the desired property from the Data Sources window, and
drop it on the appropriate control on the form to bind them.
Repeat this process for every control on the form that needs to be
bound to the business object.
The first time you drop a property from an object data source to a form, Visual Studio adds a BindingSource component to the form’s component tray and names it based on the name of your business object class. This component manages the binding between the form controls and the
business object properties.
The default property of the control that you used as your drop target is bound to the BindingSource component for the property that was dragged from the Data Sources window. You can see this by using the Properties window to examine the control’s DataBindings property.
For example, add a TextBox to an empty form. Then drag the LastName property from the Customer object data source in the Data Sources window and drop it on the TextBox control. This binds the Text property of the TextBox control to the LastName property of the Customer class by way of the CustomerBindingSource. The result is shown below.
As shown in the Properties window, the Text property of the TextBox control is now bound to the LastName property by way of the CustomerBindingSource.
The binding information for the BindingSource component and for each bound control is retained in the form’s partial class. When you perform the binding, Visual Studio sets the appropriate control properties.
The code Visual Studio adds to the partial class for the BindingSource
component is as follows
In C#:
this.customerBindingSource.DataSource =
typeof(SampleBoCSharp.Customer);
In VB:
Me.CustomerBindingSource.DataSource = GetType(SampleBoVB.Customer)
This defines that the CustomerBindingSource is associated with the Customer class in the associated project.
Visual Studio adds code to the partial class for each bound control as
follows
In C#:
this.textBox1.DataBindings.Add(
new System.Windows.Forms.Binding("Text",
this.customerBindingSource, "LastName", true));
In VB:
Me.TextBox1.DataBindings.Add( _
New System.Windows.Forms.Binding("Text", _
Me.CustomerBindingSource, "LastName", True))
This code adds a binding entry for the TextBox control. The binding entry defines that the Text property of the TextBox is bound to the LastName property in the CustomerBindingSource. The last parameter defines that formatting is enabled to allow formatting of the value.
NOTE: Although you do not normally need to look at this generated code, there is one case where you may need to know about it. If you use the renaming feature, you will see that the Rename renames only direct references to the property or method, not any occurrences in quoted strings. So if you use
the rename feature and rename LastName to CustomerLastName, your binding no longer works, because it is still using LastName. You must locate any partial class code that references the property as a quoted string and manually change its name.
Before you can successfully run the application, you need to write some code. So far, you have defined that the BindingSource component binds to a business object. And you have defined which properties of the business object are to appear in which control of the form. However, you did not define which business object it binds to.
To define which instance of the business object to bind to, assign the DataSource property of the BindingSource component to a business object instance as follows:
In C#:
Customer cust = new Customer()
{LastName = "Baggins",
FirstName = "Bilbo"};
this.customerBindingSource.DataSource = cust;
In VB:
Dim cust= New Customer With _
{.LastName = "Baggins", _
.FirstName = "Bilbo"}
Me.CustomerBindingSource.DataSource = cust
This example binds the controls in the user interface to a new instance of the Product class. Place this binding code in the form. The specific location in the form depends on when you want the binding to occur. If you want the binding to occur when the form is loaded, add this code to the form’s Load event.
By setting that instance as the DataSource for the CustomerBindingSource, the runtime uses the properties associated with that instance to populate any controls on the form bound to the CustomerBindingSource. So by writing only two lines of code, when you run your application, your form appears populated with appropriate data.
If the user changes a value in a control on the form, the runtime assigns the revised value to the associated property.
NOTE: The business object property is assigned to the value from the control when the user leaves the control. By default, if the user modifies a value and then closes the form before leaving the control, the bound property is not changed. However, if you call the Validate method, the current control’s value is assigned to its associated property even if the user does not leave the control.
Binding to New Controls
Now for the really fun part. In addition to binding to existing controls you can use the features of the Data Sources window to add new controls to a form. Or you can use it to automatically create controls for all of the business object properties.
Adding New Controls Using the Data Sources Window
If you want to add a new control to a form, you can add the control from the Forms Designer toolbox, add the associated Label control, and then bind the new control using the techniques from the preceding section.
But the Data Sources window provides a shortcut for this process. If you drag a property from the Data Sources window and drop it on the Forms Designer, Visual Studio creates the control, binds it, and creates the associated Label control. All you need to do is drag and drop!
To add a new control to a form:
1. Open the form in the Forms Designer.
2. Open the Data Sources window. Position the Data Sources window so that you can easily see its contents and the Forms Designer at the same time.
If a Forms Designer window is active, the Data Sources window changes so that each object data source and each property under the object data source displays an icon to the left of the name. This icon indicates the type of control that Visual Studio creates if you drag the item to the Forms Designer.
3. Drag a property from the Data Sources window, and drop it on the
Forms Designer.
Visual Studio automatically creates the control associated with the dropped property and binds it. It even gives the control a valid name using the property name and the control type, such as FirstNameTextBox—no lame TextBox1 name. In addition, Visual Studio creates an appropriate Label control. Visual Studio is smart about generating the text for the Label control. It breaks the property name into separate words based on either alphabetic casing or underscores.
For example, if you drag the FirstName property from the Data Sources window and drop it in the CustomerWin form, Visual Studio creates a TextBox control for the First Name and an appropriate Label control.
But what if you don’t want the property to render as a TextBox control? You can change the type of control that is rendered using the Data Sources window.
To change the default control type associated with a property:
1. Ensure that a Forms Designer is active.
2. Open the Data Sources window.
3. Click a property in the Data Sources window. The property item changes to a drop-down control list.
4. Drop down the control list and select the desired control type as shown in the prior screen shot of the Data Sources Window.
Select Customize from the list to select a control type that is not on the list. You can select just about any type of control, including third-party and
custom controls.
NOTE: Before a third-party control can be added as a control type in the Data Sources window, it must first be added to the Forms Designer toolbox.
When you drag the control from the Data Sources window to the Forms Designer, Visual Studio renders the type of control you selected as the default control type for the property. The property retains its default control type in the Data Sources window.
Creating a Form from the Data Sources Window
But wait—there’s more! You can use the Data Sources window to create all the controls for a business object and bind them.
To create a new bound form:
1. Add a new Windows Form to your project.
2. Open the Data Sources window. Position the Data Sources window so that you can easily see its contents and the Forms Designer window at the same time.
3. In the Data Sources window, click the object data source you want
to bind to this form. The item changes to a drop-down control list.
4. Use the drop-down control list to define how Visual Studio renders controls on the form for this object data source.
The class object data source can be rendered as Details, DataGridView, or None, or you can select Customize from the control list to select a control type that is not on the list.
For a data entry form, set the control type for the object data source to Details. Visual Studio renders individual controls for each property in the object data source, along with associated Label controls. Select DataGridView to render the properties in the object data source as columns in a grid.
5. Drag the object data source node from the Data Sources window and drop it on the form.
NOTE: If you plan to use Panel or other container controls on the form, place the Panel controls or other containers on the form first, and then drag the object data source node and drop it on the desired container.
Bang! Visual Studio automatically creates the controls as you specified and binds them. If you selected Details rendering, Visual Studio creates a control based on the default control type for each object data source property in the Data Sources window. It sets each control’s Name property based on the name of the associated business object property and control type. Visual Studio also defines an appropriate Label control for each control it creates. If you selected DataGridView rendering, Visual Studio defines a grid with appropriate columns and column header text.
For example, if you set up the Customer object data source to render as Details and then drag the Customer node from the Data Sources window and drop it on a form, Visual Studio creates a TextBox control for every property, binds it, names it, and creates a Label control, as shown below.
Notice that this process created two components in the form’s component tray. The BindingSource is the component that manages the binding. The BindingNavigator added VCR-style controls to the top of the form. This type of user interface is not recommended for most business applications. (How often does a user want to sequentially navigate through every customer, for example?) You can delete the BindingNavigator component, and Visual Studio automatically deletes the VCR-style controls.
The labels created for the controls are generated based on the property names. Visual Studio is smart enough to add spaces between words based on underscores or alphabetic casing. This provides a great starting point for your user interface.
The controls are added in alphabetical order, which may not be the most logical order or placement for your users. You can move and size the controls as desired. After you have the controls in their desired order, use the Tab Order view to reset the tab order.
All you need then are those two lines of code in the form’s Load event to
define the instance of the business object that is bound to the controls:
In C#:
Customer cust = new Customer()
{LastName = "Baggins",
FirstName = "Bilbo"};
this.customerBindingSource.DataSource = cust;
In VB:
Dim cust= New Customer With _
{.LastName = "Baggins", _
.FirstName = "Bilbo"}
Me.CustomerBindingSource.DataSource = cust
When you run the application, the runtime automatically populates the
controls on the form.
The Data Sources window allows you to create all the controls on a form and bind them to a business object with one drag-and-drop operation and two lines of code. It has the flexibility to allow you to define the type of control to render for each property in the object data source.
Using these techniques can make quick work of building and maintaining
your user interface.
(Based on an except from "Doing Objects in Visual Basic 2005".)
Enjoy!