jmasterx
jmasterx

Reputation: 54113

Adding logic to a sub form in Access?

I have a sub form in Access: enter image description here enter image description here

The CopyNo is a combobox that lets me select from the MovieCopies table. When I select one, I want the Title field to show the correct movie title associated to that copy's movie ID. I also want the format to show. When I select from DaysRented combobox, if I select 1 and the movie is New, I want it to display the price, if it is regular for 3 days display the correct price etc.

I'm just not sure how to give logic to the comboboxes.

If anyone could point me in the right direction of how to do this sort of thing in Access 2007 I'd really appreciate it.

Thanks

Upvotes: 0

Views: 268

Answers (1)

HK1
HK1

Reputation: 12210

Something like this:

Private Sub cboCopyNo_AfterUpdate()
    If Nz(Me.cboCopyNo, "") <> "" Then
        Me.txtTitle = DLookup("Title", "MovieMaster", "MovieID = " & Me.cboCopyNo)
    End If
End Sub

Private Sub cboDaysRented_AfterUpdate()
   If Nz(Me.cboDaysRented, 0) > 0 Then
      Dim strType as String
      strType = DLookup("[Type]", "MovieMaster", "MovieID = " & Me.cboCopyNo)
      If Me.cboDaysRented = 1 Then
          Me.txtPrice = DLookup("Price1Day", "Price", "[Type] = '" & strType & "'")
      Else
          Me.txtPrice = DLookup("Price3Day", "Price", "[Type] = '" & strType & "'")
      End If
   End If
End Sub

Couple notes. Some of your field names are reserved words in certain databases, such as "Type". I highly recommend you try to use field names that are not reserved words in Access or SQL server.

DLookups are not necessarily the fastest way to lookup data but will likely be fast enough for what you're trying to do here. Sometimes I create my own DAO recordset and lookup the values I want rather than using DLookup. It's basically like writing your own DLookup function.

DLookup uses SQL language so your syntax in the third argument, the WHERE clause, needs to match SQL. If the field in your WHERE clause is text/string you'll need to use a single quote on either side of the value (as shown above around the strType variable). If it is a number field you will not need the quotes. If it's a date you'll need hash signs (#).

Upvotes: 2

Related Questions