Home
Search
 
What's New
Index
Books
Links
Q & A
Newsletter
Banners
 
Feedback
Tip Jar
 
C# Helper...
 
XML RSS Feed
Follow VBHelper on Twitter
 
 
 
MSDN Visual Basic Community
 
 
 
 
TitleBuild master/detail records using an auto-incremented key
Keywordsmaster/detail, master, detail, autoincrement, auto-increment, autonumber, auto-number
CategoriesDatabase
 
Create the master record, which contains the auto-incremented value. Set the Recordset's Bookmark property to its LastModified property to refetch the newly created record. Use the record's key value to create the detail records.
 
' Create the master and detail records.
Private Sub Command1_Click()
Dim dbname As String
Dim db As Database
Dim master_rs As Recordset
Dim detail_rs As Recordset
Dim pos As Integer
Dim details As String
Dim one_line As String

    ' Open the database.
    dbname = App.Path
    If Right$(dbname, 1) <> "\" Then dbname = dbname & "\"
    dbname = dbname & "Data.mdb"
    Set db = DBEngine.OpenDatabase(dbname)

    ' Create the master record.
    Set master_rs = db.OpenRecordset( _
        "MasterTable", dbOpenTable)

    master_rs.AddNew
    master_rs!Name = txtName.Text
    master_rs!URL = txtURL.Text
    master_rs.Update

    ' Fetch the new record.
    master_rs.Bookmark = master_rs.LastModified

    ' Create the detail records.
    Set detail_rs = db.OpenRecordset( _
        "DetailTable", dbOpenTable)

    details = Trim$(txtDetails.Text)
    Do While Len(details) > 0
        pos = InStr(details, vbCrLf)
        If pos = 0 Then
            one_line = details
            details = ""
        Else
            one_line = Left$(details, pos - 1)
            details = Mid$(details, pos + Len(vbCrLf))
        End If

        detail_rs.AddNew
        detail_rs!ID = master_rs!ID
        detail_rs!TextLine = one_line
        detail_rs.Update
    Loop
    
    master_rs.Close
    detail_rs.Close

    MsgBox "Records created"
End Sub
 
 
Copyright © 1997-2010 Rocky Mountain Computer Consulting, Inc.   All rights reserved.
  Updated