S.Gold
S.Gold

Reputation: 9

C# Error Message:Cannot insert the value NULL into column 'Id

I develop a program who save a picture. But I get this error message:

Cannot insert the value NULL into column 'Id'

private void savepicture()
{  
    if(pictureBox1.Image != null)
    {
        MemoryStream ms = new MemoryStream();
        pictureBox1.Image.Save(ms, pictureBox1.Image.RawFormat);
        byte[] a = ms.GetBuffer();
        ms.Close();
        cm.Parameters.Clear();
        cm.Parameters.AddWithValue("@picture", a);
        cm.CommandText = "insert into Bild (FileName,Datei) values ('" + label1.Text.ToString() + "',@picture )";

        sc.Open();
        cm.ExecuteNonQuery(); // i get here the error message
        sc.Close();
        label1.Text = "";
        pictureBox1.Image = null;
        MessageBox.Show("Bild wurde gespeichert !");
    }
}

Upvotes: 0

Views: 1704

Answers (2)

Ionuț
Ionuț

Reputation: 21

I cannot add comments so i will answer here. If your Id is the primary key, you either insert it yourself or use the identity option (auto increment):

  1. add the identity option to the key from ssms. If you want to do it by query follow the answer given here https://dba.stackexchange.com/questions/128433/add-autoincrement-to-existing-pk

  2. in your insert statement do insert into Bild (Id,FileName,Datei) values ([your id], 'val1', 'val2').

Note: You have to specify the Id you want to insert if your primary key does not have an way of doing it itself (auto increment)

Upvotes: 0

Roxy'Pro
Roxy'Pro

Reputation: 4454

Before anything you should check for a structure of your table Bild, there you probably have a column called Id which is constraint and can not be a null.

And by reading your code I can not see on next line that you are supplying 'Id' to your sql:

cm.CommandText = "insert into Bild (FileName,Datei) values ('" + label1.Text.ToString() + "',@picture )";

What you should do here is next:

  • Send id from your code to a sql (create variable and include it in insert command) depending of your column type (int, guid or whatever, so if you are using int you should incremet your variable which will hold value for next 'Id' in your database, or if it is Guid you should create new Guid for every new row using Guid.NewGuid method )
  • Edit id column on Sql and apply AUTO_INCREMENT keyword to perform an auto-increment feature, example :

    Alter TABLE Bild( id int NOT NULL AUTO_INCREMENT, rest of columns );

Or you might apply next steps in case you are using Microsoft SQL and I guess you do because I can see you are using SqlCommand.CommandText Property in your C# code.

Presumably you are in the design of the table. If not: right click the table name - "Design". Click the required column. In "Column properties" (at the bottom), scroll to the "Identity Specification" section, expand it, then toggle "(Is Identity)" to "Yes". enter image description here

Upvotes: 2

Related Questions