PRB: Data Bindings Lost When ADO Recordset Is ClosedID: Q192383
|
If you have controls that are bound to a closed recordset and you then open (or re-open) that recordset, the controls do not display data from the recordset. Bound TextBox controls display what was in the TextBox before the recordset was closed. Bound Grid controls appear blank.
After you have opened (or re-opened) your recordset, you must re-bind your
controls in order to display data from that recordset.
- or -
You can use the Requery method on the recordset instead of closing and re-
opening the recordset without needing to re-bind your controls.
This behavior is by design.
Control Name
----------------------------------
Textbox txtCustomerID
Textbox txtCity
DataGrid gridCustomers
CommandButton cmdModifyData
CommandButton cmdCloseOpen
CommandButton cmdRequery
Const strPathToNWind As String = "C:\Path\To\NWind.MDB"
Dim cnNWind As ADODB.Connection
Dim rsCustomers As ADODB.Recordset
Private Sub Form_Load()
Dim strConn As String
Dim strSQL As String
cmdModifyData.Caption = "Modify Data"
cmdCloseOpen.Caption = "Close / Open"
cmdRequery.Caption = "Requery"
strConn = "Provider=Microsoft.Jet.OLEDB.3.51;" & _
"Data Source=" & strPathToNWind & ";"
strSQL = "SELECT CustomerID, City FROM Customers"
Set cnNWind = New ADODB.Connection
cnNWind.CursorLocation = adUseClient
cnNWind.Open strConn
Set rsCustomers = New ADODB.Recordset
rsCustomers.Open strSQL, cnNWind, adOpenStatic, _
adLockReadOnly, adCmdText
txtCustomerID.DataField = "CustomerID"
Set txtCustomerID.DataSource = rsCustomers
txtCity.DataField = "City"
Set txtCity.DataSource = rsCustomers
Set gridCustomers.DataSource = rsCustomers
End Sub
Private Sub ReBindMyControls()
Set txtCustomerID.DataSource = rsCustomers
Set txtCity.DataSource = rsCustomers
Set gridCustomers.DataSource = rsCustomers
End Sub
Private Sub cmdModifyData_Click()
Dim strSQL As String
Dim strNewCity As String
Dim intRecordsAffected As Integer
strNewCity = InputBox("Enter a new value for the city")
If strNewCity <> "" Then
strSQL = "UPDATE Customers " & _
"SET City = '" & strNewCity & "' " & _
"WHERE CustomerID = '" & rsCustomers!CustomerID & "'"
cnNWind.Execute strSQL, intRecordsAffected, adExecuteNoRecords
MsgBox intRecordsAffected & " record(s) affected"
Else
MsgBox "No update performed"
End If
End Sub
Private Sub cmdCloseOpen_Click()
rsCustomers.Close
rsCustomers.Open
'ReBindMyControls
MsgBox "Recordset reopened" & vbCrLf & _
"Current customer's city: " & rsCustomers!City
End Sub
Private Sub cmdRequery_Click()
rsCustomers.Requery
MsgBox "Recordset reopened" & vbCrLf & _
"Current customer's city: " & rsCustomers!City
End Sub
Private Sub Form_QueryUnload(Cancel As Integer, UnloadMode As _
Integer)
rsCustomers.Close
Set rsCustomers = Nothing
cnNWind.Close
Set cnNWind = Nothing
End Sub
ReBindMyControls
Keywords : kbcode kbDataBinding kbVBp600
Version : WINDOWS:6.0
Platform : WINDOWS
Issue type : kbprb
Last Reviewed: June 2, 1999