1

I am trying to create an INSERT INTO query, that which creates a value in a table with the value null; however, this is not working.

This is the code:

cmd = new SqlCommand("INSERT INTO Questions ([Student_ID],[Teacher_ID],[Question],[Answer],[Answered]) VALUES (@Student_ID,@Teacher_ID,@Question,@Answer,@Answered)", con);

cmd.Parameters.AddWithValue("@Student_ID", FrmLogIn.User_ID);
cmd.Parameters.AddWithValue("@Teacher_ID", cmboxTeacherChoice.SelectedItem.ToString());
cmd.Parameters.AddWithValue("@Question", tbStudentQuestion.Text);
cmd.Parameters.AddWithValue("@Answer", null);
cmd.Parameters.AddWithValue("@Answered", 0);

This code works when a value is put in cmd.Parameters.AddWithValue("@Answer", null); instead of null being there, but I need this value to be null. In the database this variable is saved as a nvarchar(MAX) and is allowed nulls, am I doing something incorrect? Please let me know.

Any answers are appreciated, if I was unclear please inform me, thank you.

marc_s
  • 732,580
  • 175
  • 1,330
  • 1,459
F Mckinnon
  • 367
  • 1
  • 4
  • 9
  • 1
    Possible duplicate of [Exception when AddWithValue parameter is NULL](http://stackoverflow.com/questions/13451085/exception-when-addwithvalue-parameter-is-null) – McNets May 08 '17 at 18:49
  • You should check out [Can we stop using AddWithValue() already?](http://blogs.msmvps.com/jcoehoorn/blog/2014/05/12/can-we-stop-using-addwithvalue-already/) and stop using `.AddWithValue()` - it can lead to unexpected and surprising results... – marc_s May 08 '17 at 19:15
  • IF this value will always be _null_, why are you putting into the `INSERT`, you could just remove it from the statement and then not add the corresponding parameter – Mad Myche May 08 '17 at 20:09

1 Answers1

5

use DBNull.Value instead of null

Frode
  • 3,325
  • 1
  • 22
  • 32