Click here to Skip to main content
15,885,546 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
Hello Everyone,

Whenever i tried to insert values into my tables using visual studio i get a null

value in the column customersID in my Orders Table (foreign key reference Customers),

how do i get V.S to fill the column instead of a null value, am using backend

SqlServer 2008

I will be more than glad if anyone can help me out on this case

Thanx in advance.

This is the structure of my Tables

SQL
CREATE TABLE Customers(
CustomersID INT IDENTITY PRIMARY KEY,
Company NVARCHAR (50),
ContactName NVARCHAR (50),
Phone NVARCHAR (50)
)
GO

CREATE TABLE Orders(
OrdersID INT IDENTITY (1,1) PRIMARY KEY,
CustomersID INT FOREIGN KEY REFERENCES Customers(CustomersID) ON DELETE CASCADE,
OrderDate DATE,
Freight DECIMAL (10,2)
)
GO

This is my code using Visual Basic

VB
Imports System.Data.Sql
Imports System.Data.SqlClient
Public Class Form1
    Dim Query As String
    Dim MyConn As SqlConnection
    Dim Cmd As SqlCommand


 Private Sub btnAdd_Click(sender As System.Object, e As System.EventArgs) Handles btnAdd.Click
 Try
            MyConn.Open()
            Query = "INSERT INTO Customers(Company, ContactName, Phone)VALUES('" & txtCompany.Text & "','" & txtContactName.Text & "', '" & txtPhone.Text & "')"
            Cmd = New SqlCommand(Query, MyConn)
            Cmd.ExecuteNonQuery()


    Query = "INSERT INTO Orders(OrderDate, Freight)VALUES('" & txtOrderDate.Text & "','" & txtFreight.Text & "')"
            Cmd = New SqlCommand(Query, MyConn)

            txtCompany.Clear()
            txtContactName.Clear()
            txtPhone.Clear()
            txtOrderDate.Clear()
            txtFreight.Clear()

            Cmd.ExecuteNonQuery()
            MyConn.Close()
            MessageBox.Show("Data Saved")
        Catch ex As Exception
            MessageBox.Show(ex.Message)
        End Try

    End Sub
End Class


Result
CustomersID Company ContactName Phone
1 Vanguard Tom 1234556789


OrdersID CustomersID OrderDate Freight
1 NULL 1950-01-01 25000.00
Posted
Updated 9-Oct-14 8:05am
v2

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:
SQL
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):
VB
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.
 
Share this answer
 
v3
Comments
PhilLenoir 9-Oct-14 14:33pm    
If you missed it, I edited the solution, the initial submission missed a line of code. Also, the quotes around the proc name got dropped when I encoded the block.
wole2020 9-Oct-14 15:34pm    
Thanks so much
PhilLenoir 9-Oct-14 15:36pm    
No prob!
Your SQL statement for inserting into the Orders table doesn't use the CustomersID as a value. Do you think SQL Server would somehow magically know for which customer this Order should be? To prevent creating Orders without a valid foreign key reference to Customers that field should not allow NULL values.

Cheers!
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900