Microsoft KB Archive/189852

= How To Change Databindings on the Fly =

Article ID: 189852

Article Last Modified on 6/29/2004

-

APPLIES TO


 * Microsoft Visual Basic 6.0 Enterprise Edition

-



This article was previously published under Q189852



SUMMARY
Changing data bindings for a textbox requires changing the DataSource and the the DataField. Set the DataField property of the textbox to Empty prior to resetting the DataSource and the DataField. If this is not done you will encounter the following error.

"Run time Error 545

Unable to bind to field DataMember: 'fieldname'"



Step-by-Step Example
  Create a standard.exe project. Form1 is created by default. Check the following under project references:      Microsoft ActiveX Data Objects 2.0 Library Microsoft Data Binding Collection

 Place a Textbox and a CommandButton on the form.  Paste the following code in the code window for the form: Dim rsProducts As ADODB.Recordset Dim rsCustomers As ADODB.Recordset

Private Sub Command1_Click

If Text1.DataField = "CompanyName" Then Text1.DataField = Empty Set Text1.DataSource = rsProducts Text1.DataField = "ProductName" Else Text1.DataField = Empty Set Text1.DataSource = rsCustomers Text1.DataField = "CompanyName" End If

End Sub

Private Sub Form_Load 'set up recordsets Set rsProducts = New ADODB.Recordset Set rsCustomers = New ADODB.Recordset rsProducts.Open "Select * from Products", _ "Provider=Microsoft.Jet.OLEDB.3.51; " & _ "Data Source=c:\school\nwind.mdb", _ adOpenstatic, adLockOptimistic rsCustomers.Open "Select * from Customers", _ "Provider=Microsoft.Jet.OLEDB.3.51; " & _ "Data Source=c:\school\nwind.mdb", _ adOpenstatic, adLockOptimistic

Set Text1.DataSource = rsCustomers Text1.DataField = "CompanyName"

End Sub

 Run the form and press the CommandButton repeatedly. It will alternate the contents of the textbox between companyname and Productname. Alter the 'Data Source' in the Open statement above to fit your environment.

