Introduction
The .NET Framework provides a very flexible and powerful approach to databinding that cuts down a lot of redundant code and simplifies the development process significantly. Unlike the earlier databinding models, which were limited to single data source, the .NET Framework provides a read/write (two ways) link to a large number of data sources such as DataSets, DataTables, Collections, and also textboxes, checkboxes, radio buttons, and so on.
In the following object binding example, you'll see how easy it is to implement a record navigation with TierDeveloper generated objects with a single line of hand-written code. Let's say you've three textbox controls on a Windows Form and you loaded all customers in a collection by calling the getAll
method of The Customers
factory class. Here is how you might want to load customers and then bind the attributes to text controls (in your case, you might have a DataGrid
or other UI components):
Public csColl As CustomersCollection
Private Sub btnLoad_Click(ByVal sender As System.Object, _
ByVal e As System.EventArgs) _
Handles btnLoad.Click
Dim objCustomer As Customers = New Customers
Dim objFactory As CustomersFactory = New CustomersFactory
csColl = New CustomersCollection
csColl = objFactory.getAll()
txtCustomerId.DataBindings.Add("Text", csColl, "CustomerID")
txtCompanyName.DataBindings.Add("Text", csColl, "CompanyName")
txtContactTitle.DataBindings.Add("Text", csColl, "ContactTitle")
End Sub
The CurrencyManager
is used to keep data-bound controls synchronized with each other. The Position
property of CurrencyManager
is used to determine the current position of all controls. Your click event handler for the Next button might look like this:
Private Sub btnNext_Click(ByVal sender As System.Object, _
ByVal e As System.EventArgs) _
Handles btnNext.Click
Dim cm As CurrencyManager = CType(Me.BindingContext(csColl), CurrencyManager)
If cm.Position < cm.Count - 1 Then
cm.Position += 1
End If
End Sub
Private Sub btnPrev_Click(ByVal sender As System.Object, _
ByVal e As System.EventArgs) Handles btnPrev.Click
Dim cm As CurrencyManager = CType(Me.BindingContext(csColl), CurrencyManager)
If cm.Position > 0 Then
cm.Position -= 1
End If
End Sub
You might allow users to make changes to any records and then persist those changes when the user clicks the Save button. Your click event handler for the Save button might persist the changes with a single call, as illustrated below:
Private Sub btnSave_Click(ByVal sender As System.Object, _
ByVal e As System.EventArgs) Handles btnSave.Click
Dim cf As CustomersFactory = New CustomersFactory
cf.Save(csColl, 0)
End Sub
You can reach the author at iqbal@alachisoft.com.
Iqbal M. Khan works for Alachisoft, a leading software company providing O/R Mapping and Clustered Object Caching solutions for .NET. You can reach him at iqbal@alachisoft.com or visit Alachisoft at www.alachisoft.com.