Reputation: 9
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
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):
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
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
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:
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".
Upvotes: 2