Problem with inserting data

t_shar

New member
Joined
Jan 1, 2017
Messages
2
Programming Experience
Beginner
hello i have been experiencing some problems with inserting data into a table in the database. i keep getting this error: Cannot insert the value NULL into column 'location_ID', table even though i did set the location ID on auto increment
this is the code im using to insert:

this is the code im using to insert:
    private void addbtn_Click(object sender, EventArgs e)
    {
        SqlConnection con = new SqlConnection();
        SqlCommand cmd = new SqlCommand();
        cmd.Connection = con;
        cmd.CommandType = CommandType.Text;
        con.ConnectionString = Properties.Settings.Default.DatabaseConnection;
        con.Open();
       // locationIDtxtOutput = Console.WriteLine(12);
        cmd.CommandText = "insert into [dbo].[Location] (country, location_region, location_house_number, location_road_number, location_block_number, location_description) values('@country', @location_region, @location_house_number, @location_road_number, @location_block_number, @location_description)";
        cmd.Parameters.AddWithValue("@country", countryCmbx.Text);
        cmd.Parameters.AddWithValue("@location_region", regionCmbx.Text);
        cmd.Parameters.AddWithValue("@location_house_number",int.Parse(houseNumtxtInput.Text));
        cmd.Parameters.AddWithValue("@location_road_number", int.Parse(rdNumtxtInput.Text));
        cmd.Parameters.AddWithValue("@location_block_number", int.Parse(blockNumTxtInput.Text));
        cmd.Parameters.AddWithValue("@location_description", descriptiontxtInput.Text);           
        cmd.ExecuteNonQuery();
        con.Close();
    }

ps. im new to using C#, i usually use Java
 
Last edited by a moderator:
There is no mention of 'location_ID' in your code so the issue is not your code specifically. It appears that you are assuming that that column is going to be populated automatically when you insert a record. For that to happen, you'd have had to configure that column to be an identity in the database, which you must not have done.
 
i did set it to auto increment as i mentioned above
this is the code that created the table

CREATE TABLE [dbo].[Location] (
[location_id] INT IDENTITY (1, 1) NOT NULL,
[country] VARCHAR (50) NULL,
[location_region] VARCHAR (50) NULL,
[location_house_number] INT NULL,
[location_road_number] INT NULL,
[location_block_number] INT NULL,
[location_description] VARCHAR (50) NULL,
CONSTRAINT [PK_Location] PRIMARY KEY CLUSTERED ([location_id] ASC)
);
 
Back
Top Bottom