This code comes from Chapt 19, p 686 in the Creating the Recordset section and the sub PopulateFields():
Code:
If Not g_rsFormSource.BOF And Not g_rsFormSource.EOF Then
Me.txtCompanyName.SetFocus
Me!txtCompanyName.Text = g_rsFormSource.Fields("CompanyName")
Me.txtContactName.SetFocus
Me!txtContactName.Text = g_rsFormSource.Fields("ContactName")
Me.txtContactTitle.SetFocus
Me!txtContactTitle.Text = g_rsFormSource.Fields("ContactTitle")
Me.txtCustomerID.SetFocus
Me!txtCustomerID.Text = g_rsFormSource.Fields("CustomerID")
Me.txtFax.SetFocus
Me!txtFax.Text = g_rsFormSource.Fields("Fax")
Me.txtPhone.SetFocus
Me!txtPhone.Text = g_rsFormSource.Fields("Phone")
Else
' Throw an error
End If
That seemed pretty bulky to me and not very flexible, so I played around for a while and came up this this:
Code:
Dim ctlC As Control
Dim strC As String
If Not g_rsFormSource.BOF And Not g_rsFormSource.EOF Then
' For each control.
For Each ctlC In Me.Controls
If ctlC.ControlType = acTextBox Then
' Get the name of the current control
strC = ctlC.Name
ctlC.Value = Nz(g_rsFormSource.Fields(strC), "")
End If
Next ctlC
End If
It saves you the trouble of setting the focus on each control and allows you to populate controls that are not enabled. It also means that you don't have to modify the VBA every time you modify the form.
It seems to work pretty well, but if anybody has any reasons why I shouldn't take this approach, I'd like to hear it. I will add in error processing later.
Thanks,
Victor