C# System.Data.SqlClient.SqlException Cannot insert the value NULL into column ERROR FOREIGN KEY

0

Error Message showing up after trying to call foreign key, that is a primary key in another table.

There's two tables and whats supposed to link them is the foreign key.

The SQL Server database does not allow, making the identity of both the primary key and the foreign key to true so it can auto increment

System.Data.SqlClient.SqlException HResult=0x80131904 Message=Cannot insert the value NULL into column 'client_ID', table ; column does not allow nulls.

Code for the database class:

public static void AddVehicle(string serial_Number, string Make, string Model, string Year, string Color)
{
        string insStmt = "INSERT INTO VEHICLE (serial_Number, Make,  Model, Year, Color) VALUES (@serial_Number, @Make, @Model, @Year, @Color)";
        SqlConnection conn = GetConnection();
        SqlCommand insCmd = new SqlCommand(insStmt, conn);
        insCmd.Parameters.AddWithValue("@serial_Number", serial_Number);
        insCmd.Parameters.AddWithValue("@Make", Make);
        insCmd.Parameters.AddWithValue("@Model", Model);
        insCmd.Parameters.AddWithValue("@Year", Year);
        insCmd.Parameters.AddWithValue("@Color", Color);

        try 
        { 
             conn.Open(); 
             insCmd.ExecuteNonQuery(); 
        }
        catch (SqlException ex) 
        {
             throw ex; 
        }
        finally 
        { 
             conn.Close(); 
        }
}

public static List<Vehicle> GetVehicle()
{
        List<Vehicle> vehicleList = new List<Vehicle>();
        SqlConnection conn = GetConnection();
        string selStmt = "SELECT * FROM VEHICLE ORDER BY Make, Model";
        SqlCommand selcCmd = new SqlCommand(selStmt, conn);

        try
        {
            conn.Open();
            SqlDataReader reader = selcCmd.ExecuteReader();
            while (reader.Read())
            {
                Vehicle vehicle = new Vehicle();

                //vehicle.Vehicle_ID = (int)reader["Vehicle_ID"];
                vehicle.Vehicle_ID = reader["Vehicle_ID"].ToString();
                vehicle.Serial_Number = reader["Serial_Number"].ToString();
                vehicle.MAke = reader["MAke"].ToString();
                vehicle.MOdel = reader["MOdel"].ToString();
                vehicle.YEar = reader["YEar"].ToString();
                vehicle.COlor = reader["COlor"].ToString();
                vehicle.ClientID = (int)reader["ClientID"];
                vehicleList.Add(vehicle);
            }
            reader.Close();
        }
        catch (SqlException ex) { throw ex; }
        finally { conn.Close(); }

        return vehicleList;
}

Code for the windows form is:

private void Form2_Load(object sender, EventArgs e)
{
        listView.Items.Clear();
        List<Vehicle> vehicleList;

        try
        {
            vehicleList = CARDB.GetVehicle();

            if (vehicleList.Count > 0)
            {
                Vehicle vehicle;

                for (int i = 0; i < vehicleList.Count; i++)
                {
                    vehicle = vehicleList[i];
                    //listView.Items.Add(vehicle.Vehicle_ID.ToString());
                    listView.Items[i].SubItems.Add(vehicle.Vehicle_ID);
                    listView.Items[i].SubItems.Add(vehicle.Serial_Number);
                    listView.Items[i].SubItems.Add(vehicle.MAke);
                    listView.Items[i].SubItems.Add(vehicle.MOdel);
                    listView.Items[i].SubItems.Add(vehicle.YEar);
                    listView.Items[i].SubItems.Add(vehicle.COlor);
                    listView.Items.Add(vehicle.ClientID.ToString());
                }
            }
            //else { MessageBox.Show("Enter client Details", "Alert:");}
        }
        catch (Exception ex) { MessageBox.Show(ex.Message, ex.GetType().ToString()); }
}

private void btnSubmit2_Click(object sender, EventArgs e)
{
        CARDB.AddVehicle(txtSerialNumber.Text, txtMake.Text, txtModel.Text, txtYear.Text, txtColor.Text);
        txtSerialNumber.Text = "";
        txtMake.Text = "";
        txtModel.Text = "";
        txtYear.Text = "";
        txtColor.Text = "";

        this.Form2_Load(this, null);
}

SQL code for the table is:

CREATE TABLE [dbo].[Vehicle] 
(
    [Vehicle_ID]    INT IDENTITY (1, 1) NOT NULL,
    [client_ID]     INT           NOT NULL,
    [Serial_Number] NVARCHAR(MAX) NULL,
    [Make]          NVARCHAR(MAX) NULL,
    [Model]         NVARCHAR(MAX) NULL,
    [Year]          NVARCHAR(MAX) NULL,
    [Color]         NVARCHAR(MAX) NULL,

    PRIMARY KEY CLUSTERED ([Vehicle_ID] ASC),
    CONSTRAINT [FK_Vehicle_Client] 
         FOREIGN KEY ([client_ID]) REFERENCES [dbo].[Client] ([clientID])
);
c#
sql
sql-server
asked on Stack Overflow May 17, 2020 by user13561757 • edited May 17, 2020 by pinkfloydx33

1 Answer

0

Your error is in this function as I see :

public static void AddVehicle(string client_ID,string serial_Number, string Make, string Model, string 
Year, string Color)
{
    string insStmt = "INSERT INTO VEHICLE (client_ID,serial_Number, Make,  Model, Year, Color) 
    VALUES (@client_ID,@serial_Number, @Make, @Model, @Year, @Color)";
    SqlConnection conn = GetConnection();
    SqlCommand insCmd = new SqlCommand(insStmt, conn);
    insCmd.Parameters.AddWithValue("@client_ID", client_ID);
    insCmd.Parameters.AddWithValue("@serial_Number", serial_Number);
    insCmd.Parameters.AddWithValue("@Make", Make);
    insCmd.Parameters.AddWithValue("@Model", Model);
    insCmd.Parameters.AddWithValue("@Year", Year);
    insCmd.Parameters.AddWithValue("@Color", Color);

    try 
    { 
         conn.Open(); 
         insCmd.ExecuteNonQuery(); 
    }
    catch (SqlException ex) 
    {
         throw ex; 
    }
    finally 
    { 
         conn.Close(); 
    }
}

You are missing the client_ID in the insert SQL statement, hence you get the error of Client Id being null.

You need to pass client_ID to the Add Vehicle function or your function INSERT statement will definitely fail.

answered on Stack Overflow May 17, 2020 by Umar Aftab

User contributions licensed under CC BY-SA 3.0