Adding events and handlers to controls created at runtime
Posted on 2004-08-31
I'm trying to make an advanced search engine for a customer account database. This is Win2k, Access 2000, VB6. It starts with a form containing a text box and a command button. The button will create a new form that contains a bunch of label controls that display the search results. I want each of these labels to respond to the double click event and pull up a form displaying all the info for the record that was clicked.
Can this be done in a similar fashion with Visual Basic?
I have searched the Internet and the search results all want to show me how to attach code to a command button on a form that is being created in design view, but I already know how to do that.
I have already created the form and the controls showing the search results (thanks to some help from this website) and all I have left is to attach the double click event listeners to the controls and I'll be all set.
Here is the code that is attached to the search command button if this helps to clarify where I am at.
Option Compare Database
Private Sub Search_Click()
Dim frmSearchResults As Form
Dim db As DAO.Database
Dim rs As DAO.Recordset
Dim cl, cl2, cl3 As Control
Dim strSQL, strFormName, strLastRecord As String
Dim clrRed, clrBlack As Long
clrRed = RGB(255, 0, 0)
clrBlack = RGB(0, 0, 0)
Set frmSearchResults = CreateForm(, "frmResults")
strFormName = frmSearchResults.Name
frmSearchResults.RecordSelectors = False
frmSearchResults.NavigationButtons = False
Set cl = CreateControl(strFormName, acLabel, acDetail, "", "", 100, 100, 5000, 200)
cl.Caption = "Search Results for: '" & Forms.frmSearch.Text6 & "'"
Set db = CurrentDb()
strSQL = "SELECT * FROM dbo_mcaccount WHERE acct_nam LIKE '*" & Forms.frmSearch.Text6 & "*' ORDER BY acct_nam"
Set rs = db.OpenRecordset(strSQL)
If Not rs.EOF Then
x = 1
Do While Not rs.EOF
If Not (rs!acct_nam = strLastRecord) Then ' Adds a line between records with different acc names
Set cl = CreateControl(strFormName, acLine, acDetail, "", "", 50, 200 + x * 200, 7000, 0)
Set cl = CreateControl(strFormName, acLabel, acDetail, "", "", 200, 200 + x * 200, 3000, 200)
Set cl2 = CreateControl(strFormName, acLabel, acDetail, "", "", 3000, 200 + x * 200, 4000, 200)
Set cl3 = CreateControl(strFormName, acLabel, acDetail, "", "", 5500, 200 + x * 200, 2000, 200)
cl.OnDblClick = "[Event Procedure]" ' THIS DOESN'T DO ANYTHING
x = x + 1
strLastRecord = rs!acct_nam
cl.Caption = rs!acct_nam ' display customer info on the label controls
cl2.Caption = rs!acct_alias_nam
cl3.Caption = rs!acct_num
If rs!status_cd = "A" Then ' If customer is active, then display in black, otherwise red for non-active
cl.ForeColor = clrBlack
cl2.ForeColor = clrBlack
cl3.ForeColor = clrBlack
cl.ForeColor = clrRed
cl2.ForeColor = clrRed
cl3.ForeColor = clrRed
DoCmd.OpenForm (strFormName) ' open form in form-view