The easiest way to do this is to do the first insert with a stored procedure, returning the ID of the new customer record.
Stored proc:
CREATE PROCEDURE prc_AddCustomer
@Company NVARCHAR (50),
@ContactName NVARCHAR (50),
@Phone NVARCHAR (50)
AS
BEGIN
INSERT INTO Customers(Company, ContactName, Phone)VALUES(Company, @ContactName, @Phone)
RETURN @@IDENTITY
END
GO
Call the procedure (note parameterize query to avoid SQL Injection):
Dim Cmd As New SqlCommand("prc_AddCustomer", MyConn)
Dim lID as Long = 0
...
Cmd.CommandType = Data.CommandType.StoredProcedure
Cmd.Parameters.AddWithValue("@Company", txtCompany.Text)
Cmd.Parameters.AddWithValue("@ContactName", txtContactName.Text)
Cmd.Parameters.AddWithValue("@Phone", txtPhone.Text)
Cmd.Parameters.Add( _
New SqlParameter("@ReturnValue", _
Data.SqlDbType.Int))
Cmd.Parameters.Item("@ReturnValue").Direction = _
Data.ParameterDirection.ReturnValue
MyConn.Open()
Cmd.ExecuteNonQuery()
lID=CInt(Cmd.Parameters.Item("@ReturnValue").Value)
You can now use the returned ID that's in "lID".
Notes:
You could do both insert in the one stored procedure, but this might reduce the reusability.
Always surround your DB access with a Try/Catch block.